Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

return iterator from std::set::insert() is const? [duplicate]

Tags:

c++

stl

According to the C++ reference, set::insert is supposed to return pair where the iterator points to either the newly inserted element, or the existing element if such existed.

But I'm having a problem assigning to the iterator, as this simple examples shows:

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

I've tried G++ and Clang and neither works.

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

I can't find anything in the documentation that indicates that the iterator should deference to a const object, and nothing in the type signature would indicate this either. Can someone help me understand why this doesn't work?

like image 584
drwowe Avatar asked Apr 30 '13 11:04

drwowe


3 Answers

For std::set, both its associated iterator and const_iterator types are constant bidirectional iterators. The reason for this is because std::set is ordered. If you were to modify an element of the set though an iterator, you would be breaking that ordering.

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

Since you're inserting 5 with insert(5), there's no reason to dereference the iterator and assign 5 to it.

like image 56
Joseph Mansfield Avatar answered Oct 14 '22 15:10

Joseph Mansfield


You can't modify a set's members in place. It's an ordered container. Its iterators are not assignable.

like image 20
huskerchad Avatar answered Oct 14 '22 16:10

huskerchad


In C++11, set iterators refer to const types (see set reference). If you think about it it makes sense, as a set stores its element ordered, and simply changing a certain element would most likely violate the ordering constraints.

like image 21
misberner Avatar answered Oct 14 '22 17:10

misberner