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

前端 未结 8 1169
甜味超标
甜味超标 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:35

    Because a std::set manages the order of it's elements, it prohibits the user to change it's elements through it's iterators. Which means it's begin() and end() methods return a const_iterator. You're only allowed to read the element pointed to by that iterator, not modify it (it's const) which is what doubler() is trying to do.

    A solution would be to just use std::vector and std::sort to order it yourself:

    #include 
    #include 
    #include 
    
    class A {
        int a;
    public:
        A(int a) : a(a) {}
        int getA() const { return a; }
        void setA(int a) { this->a = a; }
        bool operator<(const A & b) const { return a s1(mynumbers, mynumbers+6);
        std::sort(s1.begin(), s1.end());
        std::for_each(s1.begin(), s1.end(), doubler());
        std::for_each(s1.begin(), s1.end(), myprinter());
        return 0;
    }
    

提交回复
热议问题