std::fill 函数
fill函数的作用是:将一个区间的元素都赋予val值。函数参数:fill(first,last,val);//first为容器的首迭代器,last为容器的末迭代器,val为将要替换的值。
template <class ForwardIterator, class T>
void fill (ForwardIterator first, ForwardIterator last, const T& val);
函数参数:
ForwardIterator first:迭代器中的起始位
ForwardIterator last: 迭代器中的中的终止位
const T& val: 设定值
返回值:无
Assigns val to all the elements in the range [first,last)
. The behavior of this function template is equivalent to:
std::fill 函数功能也就相当于以下函数:
template <class ForwardIterator, class T>
void fill (ForwardIterator first, ForwardIterator last, const T& val)
{
while (first != last) {
*first = val;
++first;
}
}
举个例子:
// 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
fill_n函数的作用是:给你一个起始点,然后再给你一个数值count和val。把从起始点开始依次赋予count个元素val的值。
注意: 不能在没有元素的空容器上调用fill_n函数
template <class OutputIterator, class Size, class T>
OutputIterator fill_n (OutputIterator first, Size n, const T& val);
函数参数:
OutputIterator first: 迭代器的起始位
Size n: 需要赋值的个数
const T& val: 设定值
返回值: 迭代器本身
Assigns val to the first n elements of the sequence pointed by first. The behavior of this function template is equivalent to:
template <class OutputIterator, class Size, class T>
OutputIterator fill_n (OutputIterator first, Size n, const T& val)
{
while (n>0) {
*first = val;
++first; --n;
}
return first; // since C++11
}
举个例子:
// fill_n example
#include <iostream> // std::cout
#include <algorithm> // std::fill_n
#include <vector> // std::vector
int main () {
std::vector<int> myvector (8,10); // myvector: 10 10 10 10 10 10 10 10
std::fill_n (myvector.begin(),4,20); // myvector: 20 20 20 20 10 10 10 10
std::fill_n (myvector.begin()+3,3,33); // myvector: 20 20 20 33 33 33 10 10
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: 20 20 20 33 33 33 10 10