Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there an operational difference between std::set::iterator and std::set::const_iterator?

For most containers, the iterator type provides read-write access to values in the container, and the const_iterator type provides read-only access. However, for std::set<T>, the iterator type cannot provide read-write access, because modifying a value in the set (potentially) breaks the container invariants. Therefore, in std::set<T>, both iterator and const_iterator provide read-only access.

This leads me to my question: Is there any difference between the things you can do with a std::set<T>::iterator and the things you can do with a std::set<T>::const_iterator?

Note that in C++11, the manipulation methods of containers (e.g., erase) can take const_iterator arguments.

like image 569
John Bartholomew Avatar asked Sep 05 '12 14:09

John Bartholomew


People also ask

What is the difference between const iterator and iterator?

There is no performance difference. A const_iterator is an iterator that points to const value (like a const T* pointer); dereferencing it returns a reference to a constant value ( const T& ) and prevents modification of the referenced value: it enforces const -correctness.

What is an std::set?

std::set is an associative container that contains a sorted set of unique objects of type Key . Sorting is done using the key comparison function Compare. Search, removal, and insertion operations have logarithmic complexity.

Is std::set ordered?

Yes, std::set stores its elements in such a way that iterating over the elements will be done in sorted order (and the call to std::adjacent_find is to show that std::set stores unique items as well).


1 Answers

No, there's not much much functional difference between them. Of course, there used to be back in C++03, when set<T>::iterator didn't return a const T&. But once they changed it, they were stuck with two different kinds of iterators that both do the same thing.

Indeed, the standard is quite clear that they have identical functionality (to the point where they can be the same type, but aren't required to be). From 23.2.4, p. 6:

iterator of an associative container is of the bidirectional iterator category. For associative containers where the value type is the same as the key type, both iterator and const_iterator are constant iterators. It is unspecified whether or not iterator and const_iterator are the same type. [ Note: iterator and const_iterator have identical semantics in this case, and iterator is convertible to const_iterator. Users can avoid violating the One Definition Rule by always using const_iterator in their function parameter lists. —end note ]

like image 131
Nicol Bolas Avatar answered Sep 28 '22 06:09

Nicol Bolas