Humam Helfawi Humam Helfawi - 4 months ago 12
C++ Question

Checking if iterator is not assigned to item when there is no specific container

I want to search for a value in two

std::vector
's. If it was found in one of them I want to return its iterator. If not, I want to return some value which indicates that it was not found.

In normal situation where only one
std::vector
is involved, I would return
std::vector::end
. What should I do in this situation?

Normal situation:

auto find_ten=[](const std::vector<int>& v){
return std::find(v.cbegin(),v.cend(),10);
}


My situation:

auto find_ten=[](const std::vector<int>& v1,const std::vector<int>& v2){
auto it1=std::find(v1.cbegin(),v1.cend(),10);
if(it1==v1.cend()){
auto it2=std::find(v2.cbegin(),v2.cend(),10);
if(it2==v2.cend()){
//What should I return here??
}
return it2;
}
return it1;
}


I want to return something that I can check it later to know that the number
10
was not found in any of them.

Answer

Since C++14 you are allowed to compare value-initialized iterators if they meet the ForwardIterator category or stronger (see [forward.iterators] paragraph 2). A value-initialized iterator is the equivalent of a null pointer, so you can use:

    if(it2==v2.cend()){
         return std::vector<int>::iterator{};
    }

And then the caller can do:

std::vector<int>::iterator not_found{};
auto find_ten = ...
if (find_ten != not_found)
{
  ...
}