您的位置:首页 > 编程语言 > C语言/C++

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

2015-05-02 19:41 260 查看

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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: