代码片段----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
阅读全文
0 0
- 代码片段----std::for_each
- std::for_each
- std::for_each
- C++ std::for_each
- std::for_each()的奇怪现象
- 利用std::for_each 定义宏函数
- C++中std::for_each的使用
- std::stable_sort 和 std::for_each 的用法[转]
- 代码片段
- 代码片段
- 代码片段
- 代码片段
- 片段代码
- 代码片段
- 代码片段
- 代码片段
- 代码片段
- 代码片段
- Servlet简介及其生命周期详解
- 数据结构实验1-日期:9月8日
- 爬格子呀4-4
- 我的阿里秋招之路——阿里实习offer+校招offer
- 设计模式-适配器模式 C++实现
- 代码片段----std::for_each
- ssh pom.xml
- hdu 6085 Rikka with Candies bitset优化计数
- python类与对象part2
- python设计模式之代理模式
- 基数排序算法
- 构建iOS开发环境
- libvirt XLC driver --pass-fds
- 计算机的一些笑话