Consider the following code:
#include <vector> #include <iostream> int main() { std::vector<int> vec{1,2,3,5}; for(auto it=vec.cbegin();it!=vec.cend();++it) { std::cout << *it; // A typo: end instead of cend if(next(it)!=vec.end()) std::cout << ","; } std::cout << "\n"; }
Here I've introduced a typo: in the comparison I called vec.end()
instead of vec.cend()
. This appears to work as intended with gcc 5.2. But is it actually well-defined according to the Standard? Can iterator
and const_iterator
be safely compared?
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.
we can use == and != to compare to valid iterators into any of the library containers. The section also tells us that iterators for string and vector support relational operators (aka iterator arithmetic) which include >, >=, <, <=.
To compare the values that two iterators are pointing at, dereference the iterators first, and then use a comparison operator. Operator= -- Assign the iterator to a new position (typically the start or end of the container's elements).
In general: If you pass a non- const reference, the caller doesn't know if the iterator is being modified. You could pass a const reference, but usually iterators are small enough that it gives no advantage over passing by value.
Surprisingly, C++98 and C++11 didn't say that you can compare a iterator
with a const_iterator
. This leads to LWG issue 179 and LWG issue 2263. Now in C++14, this is explicitly permitted by § 23.2.1[container.requirements.general]p7
In the expressions
i == j i != j i < j i <= j i >= j i > j i - j
where
i
andj
denote objects of a container'siterator
type, either or both may be replaced by an object of the container'sconst_iterator
type referring to the same element with no change in semantics.
See §23.2.1, Table 96:
X::iterator
[...]
any iterator category that meets the forward iterator requirements.
convertible to
X::const_iterator
So, yes, it is well-defined.
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