当前位置: 代码迷 >> 综合 >> for_each
  详细解决方案

for_each

热度:99   发布时间:2024-01-13 07:25:00.0
  1. for_each //遍历容器
  • 函数原型:for_each(iterator begin, iterator end, _func)
  • begin 开始迭代器
  • end 结束迭代器
  • _func函数或者函数对象
  • #include<iostream>
    #include<vector>
    #include<algorithm>
    using namespace std;void print1(int val)
    {cout << val << " ";
    }//仿函数
    class print2
    {
    public:void operator()(int val){cout << val << " ";}
    };
    void test1()
    {vector<int> v;for (int i = 0; i < 10; i++){v.push_back(i);}for_each(v.begin(), v.end(), print1);cout << endl;for_each(v.begin(), v.end(), print2());cout << endl;
    }
    int main()
    {test1();return 0;
    }