Why does std::set seem to force the use of a const_iterator?

后端 未结 4 1581
花落未央
花落未央 2020-12-18 17:51

Consider the simple program below, which attempts to iterate through the values of a set using NON-const references to the elements in it:

#include 

        
相关标签:
4条回答
  • 2020-12-18 18:06

    A set is like a map with no values, only keys. Since those keys are used for a tree that accelerates operations on the set, they cannot change. Thus all elements must be const to keep the constraints of the underlying tree from being broken.

    0 讨论(0)
  • 2020-12-18 18:07

    std::set uses the contained values to form a fast data structure (usually, a red-black tree). Changing a value means the whole structure needs to be altered. So, forcing constness, std::set prevents you from pushing it into a non-usable state.

    0 讨论(0)
  • 2020-12-18 18:07

    From the cpp reference:

    In a set, the value of an element also identifies it (the value is itself the key, of type T), and each value must be unique. The value of the elements in a set cannot be modified once in the container (the elements are always const), but they can be inserted or removed from the container.

    0 讨论(0)
  • 2020-12-18 18:20

    The behaviour is by design.

    Giving you a non-const iterator could inspire you to change the element in the set; the subsequent iterating behaviour would then be undefined.

    Note that the C++ standard says that set<T>::iterator is const so the old-fashioned pre C++11 way still wouldn't work.

    0 讨论(0)
提交回复
热议问题