Marko Bencik
Marko Bencik

Reputation: 396

What does the stl find function return from deque

I'm having a std deque and searching for elements in it. My problem is that I do not understand what kind of form is the find function returning.

std::deque< DataCellHandle > dataCellHandleArray;
std::_Deque_iterator<DataCellHandle, const DataCellHandle&, const DataCellHandle*> it =
    std::find( dataCellHandleArray.cbegin(), dataCellHandleArray.cend(), releaseHandle ); // works

std::deque< DataCellHandle >::iterator itr =
    std::find( dataCellHandleArray.cbegin(), dataCellHandleArray.cend(), releaseHandle ); // does not work

I expected that either a index or a iterator will be returned.

Upvotes: 0

Views: 293

Answers (2)

lubgr
lubgr

Reputation: 38267

The return type of std::find is identical to the type of the iterators you instantiate this function template with. In your case, you pass dataCellHandleArray.cbegin() and .cend(), which is of type std::deque::const_iterator, not std::deque::iterator. Hence, this is your fix:

std::deque<DataCellHandle>::const_iterator it = ...

Note that this works out of the box with:

auto it = std::find(dataCellHandleArray.cbegin(), dataCellHandleArray.cend(),
   releaseHandle);

Note that a const_iterator can be constructed from an iterator, but not the inverse.

// Ok, iterator to const_iterator
std::deque<DataCellHandle>::const_iterator ci = dataCellHandleArray.begin();

// Ok, compare const_iterator and iterator:
assert(ataCellHandleArray.begin() == ataCellHandleArray.cbegin());

// Error, can't loose constness of the "pointee"
std::deque<DataCellHandle>::iterator ci = dataCellHandleArray.cbegin();

Upvotes: 5

Yksisarvinen
Yksisarvinen

Reputation: 22176

std::find returns object of the same type as first and last argument, which in your case is std::deque<DataCellHandle>::const_iterator

Upvotes: 6

Related Questions