[英]Which STL Algorithm should i use if I want to find something but Don't want it to return last if not found?
which STL Algorithm should i use if I want to find something but Don't want it to return last if not found? 如果我想查找某些东西,但不希望它最后返回,我应该使用哪种STL算法?
My use case is I need to find or return null in the vector of user-defined types. 我的用例是我需要在用户定义类型的向量中查找或返回null。
Find and Find_If seem to return the last item if not found. 如果未找到,则Find和Find_If似乎返回最后一项。 I need to do "someting else" if the element is not found.
如果找不到该元素,我需要做“其他”操作。
Thanks 谢谢
The .end()
if a vector does not point to the "last item", but the empty space after the last item. .end()
如果向量不指向“最后一项”),而是指向最后一项之后的空白区域。 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;
}
I don't really get what the problem is with find return end? 我真的不明白查找返回端的问题是什么? end is not the last element, but the 'one past last'.
end不是最后一个元素,而是“过去一个过去”。
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;
}
You want to return: pointer-or- NULL
. 您要返回:指针或
NULL
。 You have: iterator-or- end()
您具有:iterator-or-
end()
auto it = std::find(std::begin(x), std::end(x), 42);
return it == std::end(x) ? 0 : &*it;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.