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

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

    The problem is that you are not allowed to modify elements in a std::set. If it were possible, then how would it handle something like this:

    std::set my_set { 1, 2, 3 };
    int& foo = *(my_set.begin());
    foo = 2;
    

    Now there is two elements with value 2. That doesn't make sense in a set due to

    std::set is an associative container that contains a sorted set of unique objects of type Key.

    (emphasis mine)

    http://en.cppreference.com/w/cpp/container/set

提交回复
热议问题