Today I wrote a small predicate to find matching symbols in a container.
But I'm faced to a problem: I want to use this predicate in a std::find_if
call inside a const-method of a class, searching in a container that is a member of this class.
But I just noticed that neither std::find
nor std::find_if
are able to operate on const_iterators
!
I checked on some C++ references and it seems there is no version of std::find
or std::find_if
that accept/return const_iterators
. I just can't understand why, since from what I've seen, there is no way that these algorithms could modify the object referenced by the iterator.
Here is how is documented std::find
in the SGI implementation:
Returns the first iterator i in the range [first, last) such that *i == value. Returns last if no such iterator exists.
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.
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.
An iterator is used to point to the memory address of the STL container classes. For better understanding, you can relate them with a pointer, to some extent. Iterators act as a bridge that connects algorithms to STL containers and allows the modifications of the data present inside the container.
std::find
and std::find_if
can definitely operate on *::const_iterator
for a given container. Are you by chance looking at the signatures of those functions, and misunderstanding them?
template <class InputIterator, class Type>
InputIterator find(InputIterator first, InputIterator last, const Type& val);
Note that InputIterator
here is just a name of a template type parameter, and any const_iterator
will satisfy the requirements for it.
Or, perhaps, you're confusing const_iterator
(i.e. an iterator referencing a const value) with a const
iterator (i.e. an iterator which is itself const
)?
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