Reputation: 3025
which STL Algorithm should i use if I want to find something but Don't want it to return last if not found?
My use case is I need to find or return null in the vector of user-defined types.
Find and Find_If seem to return the last item if not found. I need to do "someting else" if the element is not found.
Thanks
Upvotes: 1
Views: 288
Reputation: 16168
I don't really get what the problem is with find return end? end is not the last element, but the 'one past last'.
you can do this to catch the not found case:
std::vector<int> a {1,2,3,4,5,6};
auto it=std::find(a.begin(), a.end(), 4); //or find if
if(it!=a.end())
{
std::cout <<"found" << std::endl;
}
else
{
std::cout << "did not find" << std::endl;
}
Upvotes: 1
Reputation: 168716
You want to return: pointer-or-NULL
. You have: iterator-or-end()
auto it = std::find(std::begin(x), std::end(x), 42);
return it == std::end(x) ? 0 : &*it;
Upvotes: 1
Reputation: 523484
The .end()
if a vector does not point to the "last item", but the empty space after the last item. If you need to do something else, just put it in a condition.
std::vector<T>::iterator it = std::find(vec.begin(), vec.end(), .....);
if (it != vec.end())
{
// object found
return *it;
}
else
{
// do something else
return NULL;
}
Upvotes: 12