Return iterator of std :: set :: insert () is const?

According to C ++, set :: insert should return a pair where the iterator points to either a newly inserted element or an existing element, if one exists.

But I have a problem assigning to an iterator, as these simple examples show:

int main() { set<int> set; *set.insert(5).first = 5; return 0; } 

I tried g ++ and Clang and did not work.

 set.cc:7:24: error: read-only variable is not assignable *set.insert(5).first = 5; ~~~~~~~~~~~~~~~~~~~~ ^ 

I cannot find anything in the documentation that indicates that the iterator should relate to the const object, and nothing in the type signature will indicate this. Can someone help me understand why this is not working?

+7
source share
3 answers

For std::set both the associated types iterator and const_iterator are constant bidirectional iterators. The reason for this is because std::set ordered. If you changed the set element, although an iterator, you would break this ordering.

Consider a std::set with ordered elements {1, 4, 8} . If you then did something like *set.insert(5).first = 10; (if it was allowed), first 5 will be inserted to get {1, 4, 5, 8} , and then the inserted element will be set to 10 to get {1, 4, 10, 8} . Now the ordering invariant has been broken.

Since you insert 5 with insert(5) , there is no reason to dereference the iterator and assign it 5 .

+13
source

You cannot change the set of items in place. This is an ordered container. Its iterators cannot be assigned.

+4
source

In C ++ 11, set iterators to const types (see install link ). If you think about it, this makes sense, since the collection retains an ordered element and simply changing a specific element will likely violate order restrictions.

+3
source

All Articles