template < class ForwardIterator, class T >
void fill ( ForwardIterator first, ForwardIterator last, const T& value );
Fill range with value
Sets value to all elements in the range [first,last).
fill_n函数模板如下:
template < class OutputIterator, class Size, class T > void fill_n ( OutputIterator first, Size n, const T& value );
Fill sequence with value
Sets value to the first n elements in the sequence pointed by first.
fill_n不检查是否有足够的空间来填充,切记使用是保证有足够的空间,不然会导致disaster。
#include<iostream> #include<algorithm> #include<vector> using namespace std; int main() { vector<int> vec(10); fill_n(vec.begin(),10,1); for(int i=0;i<vec.size();i++) cout<<vec[i]<<ends; fill(vec.begin(),vec.end(),2); for(int i=0;i<vec.size();i++) cout<<vec[i]<<ends; cout<<endl; }