I'm currently learning STL and I got some uncertainities about find and const iterators. Let's say I have a find function:
some_stl_container::const_iterator found = myContainer.find(value);
After that should I check what I got for found
against another const_iterator, or is it
valid to make a check against simply an iterator.
Basically would there be any difference between doing this:
if(found!=myContainer.cend())
and this:
if(found!=myContainer.end())
The first looks more accurate(at least to me), but the second should work fine too, right?
Constant Iterators: A const iterator points to an element of constant type which means the element which is being pointed to by a const_iterator can't be modified. Though we can still update the iterator (i.e., the iterator can be incremented or decremented but the element it points to can not be changed).
Use an iteratorvector<int>::iterator iter; An iterator is used as a pointer to iterate through a sequence such as a string or vector . The pointer can then be incremented to access the next element in the sequence. To access the value in the memory space to which the iterator is pointing, you must use * .
begin() returns an iterator to beginning while cbegin() returns a const_iterator to beginning. The basic difference between these two is iterator (i.e begin() ) lets you change the value of the object it is pointing to and const_iterator will not let you change the value of the object.
All standard library containers satisfy the requirement that Container::iterator
is convertible to Container::const_iterator
. So both comparisons are valid and will yield the same result.
From §23.2.1 - Table 96
X::iterator
...
any iterator category that meets the forward iterator requirements. convertible toX::const_iterator
.
Checking if your iterator is different from myContainer.end()
is fine. cend
and cbegin
methods are only here to explicitely obtain const iterators, so that makes no difference in your case.
Note that you could do auto found = myContainer.find(value)
in c++11 to infer the iterator type, and that some people will argue that Standard library is the correct name (not STL).
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