Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

STL algorithms and const_iterators

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.

like image 801
NewbiZ Avatar asked Oct 27 '09 17:10

NewbiZ


People also ask

What is a const_iterator?

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 the difference between Cbegin and begin?

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.

What is iterator in C++ STL?

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.


1 Answers

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)?

like image 195
Pavel Minaev Avatar answered Oct 18 '22 13:10

Pavel Minaev