代码片段----std::for_each

来源:互联网 发布:白山网络人才网 编辑:程序博客网 时间:2024/05/21 09:33

例程

#include <vector>#include <iostream>#include <algorithm>int add5(int &n){int re = n + 5;std::cout << re << " ";return n + 5;}class addClass{const int m_a;public:addClass(int _a) : m_a(_a){}void operator()(int _val) const{_val += m_a;std::cout << _val << " ";}};int main(){int a[10] = { 0,1,2,3,4,5,6,7,8,9 };std::vector<int> vec(std::begin(a), std::end(a));// 不改变 vec// 函数std::for_each(vec.begin(), vec.end(), add5);std::cout << std::endl;// 类std::for_each(vec.begin(), vec.end(), addClass(6));std::cout << std::endl;// lambda表达式std::vector<int> A(std::begin(a), std::end(a));std::vector<int> B(std::begin(a), std::end(a));std::for_each(vec.begin(), vec.end(), [&A, &B](int i) {A[i] = B[i] + 5;std::cout << "A["<<i<<"]=" <<A[i] << " ";});std::cout << std::endl;// show vecfor (auto sub : vec)std::cout << sub << " ";std::cout << std::endl;// 改变vecstd::for_each(vec.begin(), vec.end(), [&vec](int i) {vec[i] += 10;});// show vecfor (auto sub:vec)std::cout << sub<< " " ;std::cout<<std::endl;    return 0;}


运行结果:

5 6 7 8 9 10 11 12 13 14
6 7 8 9 10 11 12 13 14 15
A[0]=5 A[1]=6 A[2]=7 A[3]=8 A[4]=9 A[5]=10 A[6]=11 A[7]=12 A[8]=13 A[9]=14
0 1 2 3 4 5 6 7 8 9
10 11 12 13 14 15 16 17 18 19

原创粉丝点击