【STL】for_each示例
2015-09-05 16:32
405 查看
void myfun1(int& i) { std::cout << i << " "; } void myfun2(int i, const char* prefix) { std::cout << prefix << i << std::endl; } struct mystruct1 { void operator() (int& i) { std::cout << i << " "; } } myobject1; struct mystruct2 { const char* prefix_; mystruct2(const char* prefix): prefix_(prefix) {} void operator() (int& i) { std::cout << prefix_ << i << std::endl; } }; class myclass1 { public: void operator() (int& i) { std::cout << i << " "; } }; class myclass2 { public: const char* prefix_; myclass2(const char* prefix): prefix_(prefix){}; void operator() (int& i) { std::cout << i << " "; } }; void test_for_each() { int ar[] = {1, 2, 3, 4, 5, 6, 7, 8, 9}; std::vector<int> v(ar, ar + 9); // 一个参数的普通函数 std::cout << "myfunction1 output below: " << std::endl; for_each(v.begin(), v.end(), myfun1); std::cout << std::endl; // 二个参数的普通函数 std::cout << "myfunction2 output below: " << std::endl; for_each(v.begin(), v.end(), std::bind2nd(std::ptr_fun(myfun2), "i = ")); // 不带参的结构体 std::cout << "mystruct1 output below: " << std::endl; for_each(v.begin(), v.end(), mystruct1()); // for_each(v.begin(), v.end(), myobject1); // 这个方法也行. std::cout << std::endl; // 带参的结构体 std::cout << "mystruct2 output below: " << std::endl; for_each(v.begin(), v.end(), mystruct2("i = ")); // 不带参的类 std::cout << "myclass1 output below: " << std::endl; for_each(v.begin(), v.end(), myclass1()); std::cout << std::endl; // 带参的类 std::cout << "myclass2 output below: " << std::endl; for_each(v.begin(), v.end(), myclass2("i = ")); std::cout << std::endl; }
转自:/article/7701897.html
相关文章推荐
- 使用 HAProxy, PHP, Redis 和 MySQL 轻松构建每周上亿请求Web站点 - 技术翻译 - 开源中国社区
- 数据的持久化保存
- POJ 2376 Cleaning Shifts (区间覆盖)
- 43 Multiply Strings
- 批量(文件名)HTML文件转化成jsp文件
- 全排列与组合问题
- leetcode 274: H-Index
- 动态代理模式原理-资源
- 并行算法的基本原理
- 编译与汇编
- 博客园API
- mouseover事件mouseenter事件
- TCP/IP(2)链路层
- android mvp
- 虚拟机上网
- houdini dop中调用sop体积场的几种方法
- 傻瓜式用Eclipse连接MySQL数据库
- 条款21:必须返回对象时,别妄想返回其引用
- UC/OS II中断管理
- selenium下各浏览器的driver配置