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?
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.
You can't modify a set's members in place. It's an ordered container. Its iterators are not assignable.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With