STLalgorithm算法fill(14)


STLalgorithm算法fill(14)

原文地址:http://www.cplusplus.com/reference/algorithm/fill/

function template
<algorithm>

std::fill

template <class ForwardIterator, class T>
  void fill (ForwardIterator first, ForwardIterator last, const T& val);
Fill range with value

Assigns val to all the elements in the range [first,last).使用val填满范围内的元素。

例子:

#include <iostream>
#include <algorithm>
#include <vector>
#include <array>
using namespace std;

void fill2(){
    vector<int> vi{1,5,7,8,9,9,8,5,9};
    cout<<"at first,vi=";
    for(int &i:vi)
        cout<<i<<" ";
    cout<<endl;

    fill(vi.begin(),vi.end()-3,1000);
     cout<<"after     fill(vi.begin(),vi.end()-3,1000),\nvi=";
    for(int &i:vi)
        cout<<i<<" ";
    cout<<endl;

}


运行截图:


The behavior of this function template is equivalent to:

1
2
3
4
5
6
7
8
template <class ForwardIterator, class T>
  void fill (ForwardIterator first, ForwardIterator last, const T& val)
{
  while (first != last) {
    *first = val;
    ++first;
  }
}




Parameters

first, last
Forward iterators to the initial and final positions in a sequence
of elements that support being assigned a value of type T. The range filled is [first,last), which contains all the elements between first and last, including the element pointed by first but not the
element pointed by last.
要填充的范围。
val
Value to assign to the elements in the filled range.
填充的值。



Return value

none


Example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
// fill algorithm example
#include <iostream>     // std::cout
#include <algorithm>    // std::fill
#include <vector>       // std::vector

int main () {
  std::vector<int> myvector (8);                       // myvector: 0 0 0 0 0 0 0 0

  std::fill (myvector.begin(),myvector.begin()+4,5);   // myvector: 5 5 5 5 0 0 0 0
  std::fill (myvector.begin()+3,myvector.end()-2,8);   // myvector: 5 5 5 8 8 8 0 0

  std::cout << "myvector contains:";
  for (std::vector<int>::iterator it=myvector.begin(); it!=myvector.end(); ++it)
    std::cout << ' ' << *it;
  std::cout << '\n';

  return 0;
}

Output:

myvector contains: 5 5 5 8 8 8 0 0



Complexity

Linear in the distance between first and last: Assigns a value to each element.


Data races

The objects in the range [first,last) are modified (each object is accessed exactly once).


Exceptions

Throws if either an element assignment or an operation on an iterator throws.
Note that invalid arguments cause undefined behavior.

——————————————————————————————————————————————————————————————————

//写的错误或者不好的地方请多多指导,可以在下面留言或者点击左上方邮件地址给我发邮件,指出我的错误以及不足,以便我修改,更好的分享给大家,谢谢。

转载请注明出处:http://blog.csdn.net/qq844352155

author:天下无双

Email:coderguang@gmail.com

2014-9-11

于GDUT

——————————————————————————————————————————————————————————————————


发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注