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

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

    Because the contents of an object in an std::set determines its position. That's why std::set iterators are always const.

    Of course, it is often the case that not all members of an object have an effect on its position. A possible workaround is then to declare those members mutable. Then you can modify them using const references.

    To modify a member that does affect the object's position in a set, remove the object from the set, modify it, and add it back in.

    0 讨论(0)
  • 2021-01-13 19:45

    Based on the comments, I've learned the following so far:

    1. Why doesn't this code mutate the set?

    Because the parameter passed into the doubler method is passed by value (the C++ default), instead of by reference. Therefore, the value of each a parameter is modified, but this is not saved to the element in the container.

    2. How can the code be altered so that it will modify the set?

    Not easy to do. Sets (as opposed to other containers such as vectors, deques, lists, and arrays) maintains order to its elements. (Suppose instead that the function used in the for_each method negated every element. Then the set would be ordered backwards, and the order the set tried to maintained would be lost). Thus, if you want to modify the elements of a set you have to do so one at a time (Thank you @NathanOliver and @moooeeeep for your comments)

    Note: If the container was not a set (instead, a vector or deque), then the doubler method could be modified to the following to mutate the elements:

    void operator()(A & a) { a.setA(a.getA()*2); }
    
    0 讨论(0)
提交回复
热议问题