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

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

    You can't simply change the key of an element in a key-value store kind of a data structure. (In case of a set, it's only key, no value.)

    If you would, the element's position in the underlying container might need to be adjusted, based on the recomputed hash value in case of an unordered hash table, or a different sorting position in a binary search tree / ordered list.

    Therefore the API of the std::set requires you to erase and reinsert the item in this case.

    Which the answers to existing questions in this direction already state:

    • C++ STL set update is tedious: I can't change an element in place
    • How to update an existing element of std::set?

提交回复
热议问题