Wednesday, January 27, 2016

find_if with const_iterator

This is somewhat old topic, but I am blogging it anyways.

In C++ if you want to use find() or find_if algorithms with const_iterator instead of iterator, for e.g inside a const member function that does not alter the member contents, and if you encounter any compiler complaints regarding the same, then

confirm that the return type is also a const_iterator and not an iterator. find() and find_if are written to take iterator and const_iterator into consideration and return the results as per the STL Algorithm docs. Hence if the code also is written to work with respective iterators compiler error would be taken care of.

for e.g
uint64_t ID = 34; //sample
std::vector::const_iterator itr = std::find_if(list.begin(), list.end(), [ID](const ListType& a){ return a.ID == ID; }); //lamdba function to find the object with ID.



No comments: