Using for_each to modify std containers (even though you shouldn't)

前端 未结 8 1158
甜味超标
甜味超标 2021-01-13 18:58

I\'m taking a self-study course for C++, learning how the Standard Library works, and I want to understand how this code that uses for_each works, particularly

8条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-01-13 19:39

    This is a piece of cake with a lambda expression.

    #include 
    #include 
    #include 
    using namespace std;
    
    int main() {
        int mynumbers[] = {8, 9, 7, 6, 4, 1};
        vector s1(mynumbers, mynumbers+6);
        sort(s1.begin(), s1.end());
        for_each(s1.begin(), s1.end(), [](int &x) { x*=2; });
        for_each(s1.begin(), s1.end(), [](int x) { cout << x << ", "; });
        return 0;
    }
    
    OUTPUT:
    2, 8, 12, 14, 16, 18,
    

提交回复
热议问题