C++学习 fill和fill_n和for_each()函数的应用
2015-05-02 19:41
260 查看
C++学习 fill和fill_n函数的应用
转自:http://blog.sina.com.cn/s/blog_933dc4350100y9xn.htmlfill函数的作用是:将一个区间的元素都赋予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; }
相关文章推荐
- 多想追求简洁的极致,但是无奈的学习C++中for_each的应用
- 多想追求简洁的极致,但是无奈的学习C++中for_each的应用
- C++成员函数指针的应用(学习收录)
- C++成员函数指针的应用(学习收录)
- 【C++ STL学习之六】STL算法之for_each
- 【C++ STL学习之六】STL算法之for_each
- c++ 标准模板库 STL 算法之 for_each 函数的使用用法详解
- c++ 标准模板库 STL 算法之 for_each 函数的使用用法详解
- C++ STL 学习 :for_each与仿函数(functor)
- 【C++ STL学习之六】STL算法之for_each
- C++学习笔记(第四章 函数的应用及多文件组织 之二)
- C++学习笔记(第四章 函数的应用及多文件组织 之三)
- C++学习笔记(第四章 函数的应用 递归函数 之四)
- c++学习之函数模板应用和重载
- C++学习笔记(八):对字符的操作函数和范围for语句的使用
- C++中for_each的应用
- C++ STL 学习 :for_each与仿函数(functor)(一)
- C++ STL 学习 :for_each与仿函数(functor)
- c++学习之函数模板应用和重载
- C++ STL 学习 :for_each与仿函数(functor)(一)