简体   繁体   English

如果我想找到一些东西但不希望它最后返回,我应该使用哪种STL算法?

[英]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.

相关问题 C++ STL 映射我不希望它排序! - C++ STL map I don't want it to sort! 如果我希望它忽略重复的元素,使用哪个STL容器? - Which STL container to use if I want it to ignore duplicated elements? 如果我不想在QAbstractItemView中实现选择,应该返回什么值? - What values should I return if I don't want to implement selections in a QAbstractItemView? 如果我不想使用QMainWindow的布局,应该使用什么代替QMainWindow? QMainWindow应该在哪里首选? - What should I use instead of QMainWindow if I don't want to use QMainWindow's layout? Where should QMainWindow be preferred? 我应该将哪个STL容器用于FIFO? - Which STL container should I use for a FIFO? C ++ / STL我应该使用哪种算法来检查容器是否有重复? - C++/STL which algorithm should I use to check if a container has duplicates? 如果我没有返回未知类型的东西,我应该返回什么 - what should I return if I don't have something to return for an unknown type 在测试SFINAE时,我发现了一些我认为不应该起作用的东西 - While testing SFINAE, I found something that I don't think should work 我不想在最后一个数字/值之后使用逗号,我该如何删除它(c++,循环) - I don't want a comma after the last number/value, how do i remove it (c++, loop) 我可以使用哪个STL容器/算法来解决此问题? - Which STL container(s)/algorithm(s) could I use to solve this?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM