Humam Helfawi Humam Helfawi - 6 months ago 26
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

'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
is involved, I would return
. 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);
auto it2=std::find(v2.cbegin(),v2.cend(),10);
//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
was not found in any of them.


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:

         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)