- 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;
- }
【STL】for_each使用示例
最新推荐文章于 2024-03-22 09:49:58 发布