C++学习 fill和fill_n和for_each()函数的应用

来源:互联网 发布:天心天思网络差评 编辑:程序博客网 时间:2024/05/15 06:08

C++学习 fill和fill_n函数的应用

转自:http://blog.sina.com.cn/s/blog_933dc4350100y9xn.html
fill函数的作用是:将一个区间的元素都赋予val值。函数参数:fill(first,last,val);//first为容器的首迭代器,last为容器的末迭代器,val为将要替换的值。

例题:给你n个数,然后输入一些操作:start,end,paint。表示从start到end都赋予paint的值,并输出每一次操作后的数组状态。
代码:
#include <iostream>#include <algorithm>#include <vector>using namespace std;void print(int &elem){cout<<elem<<" ";}int main(){    vector <int> V;    int n,startpos,endpos,paint;    cin>>n;    V.resize(n);    while(cin>>startpos>>endpos>>paint)   {       fill(V.begin()+startpos-1,V.begin()+endpos,paint);       for_each(V.begin(),V.end(),print);           cout<<endl;   }   return 0;}
对for_each(V.begin(),V.end(),paint);的解释:
for_each()事实上是个function template(模板函数),其實做如下[effective STL item 41] template<typename InputIterator, typename Function>Function for_each(InputIterator beg, InputIterator end, Function f) {  while(beg != end)     f(*beg++);}



fill_n函数的作用是:给你一个起始点,然后再给你一个数值count和val。把从起始点开始依次赋予count个元素val的值。
注意: 不能在没有元素的空容器上调用fill_n函数
例题:给你n个数,然后输入一些操作:start,count,paint。表示从start开始连续填充count个数字,paint为填充的数值。
代码:
#include <iostream>#include <algorithm>#include <vector>using namespace std;void print(int &elem){cout<<elem<<" ";}int main(){    vector <int> V;    int n,start,count,paint;    cin>>n;    V.resize(n);    while(cin>>start>>count>>paint)   {       fill_n(V.begin()+start-1,count,paint);       for_each(V.begin(),V.end(),print);            cout<<endl;   }   return 0;}


再发一下关于fill_n函数的例子:
// fill_n example#include <iostream>#include <algorithm>#include <vector>using namespace std;int main () {        vector<int> myvector (8,10); // myvector: 10 10 10 10 10 10 10 10        fill_n (myvector.begin(),4,20); // myvector: 20 20 20 20 10 10 10 10        fill_n (myvector.begin()+3,3,33); // myvector: 20 20 20 33 33 33 10 10        cout << "myvector contains:";        for (vector<int>::iterator it=myvector.begin(); it!=myvector.end(); ++it)              cout << " " << *it;         cout << endl; return 0;}


0 0