Why does std::set.insert() return a non-const iterator, and yet I cannot modify it?

后端 未结 2 605
广开言路
广开言路 2021-02-04 08:55

Consider this code example:

#include 
#include 

using namespace std;

set string_set;

void foo(const string& a)
{
           


        
相关标签:
2条回答
  • 2021-02-04 09:40

    Because according to the standard, modifications through a set<>::iterator are not allowed. The standard specifically allows set<>::iterator and set<>::const_iterator to be the same type. And although it doesn't require them to be the same type, it does require the value_type of set<>::iterator to be const.

    The reason for this, of course, is that any modifications to the value could invalidate the invariants of std::set<>.

    0 讨论(0)
  • 2021-02-04 09:51

    From the standard :

    23.3.3

    A set is a kind of associative container that supports unique keys (contains at most one of each key value) and provides for fast retrieval of the keys themselves. Class set supports bidirectional iterators.

    This is also from the standard :
    typedef implementation defined iterator; // See 23.1

    The real implementation of set::iterator is a constant iterator in order to keep the requirement to have unique keys. Otherwise you could change the values in set to all the same values.

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