C++ 检查 std::vector 是否包含某个对象?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3450860/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
check if a std::vector contains a certain object?
提问by jmasterx
Is there something in <algorithm>
which allows you to check if a std:: container contains something? Or, a way to make one, for example:
有什么东西<algorithm>
可以让您检查 std:: 容器是否包含某些东西?或者,一种制作方法,例如:
if(a.x == b.x && a.y == b.y)
return true;
return false;
Can this only be done with std::map
since it uses keys?
std::map
因为它使用密钥,所以只能这样做吗?
Thanks
谢谢
回答by You
Checking if v
contains the element x
:
检查是否v
包含元素x
:
#include <algorithm>
if(std::find(v.begin(), v.end(), x) != v.end()) {
/* v contains x */
} else {
/* v does not contain x */
}
Checking if v
contains elements (is non-empty):
检查是否v
包含元素(非空):
if(!v.empty()){
/* v is non-empty */
} else {
/* v is empty */
}
回答by AshleysBrain
If searching for an element is important, I'd recommend std::set
instead of std::vector
. Using this:
如果搜索元素很重要,我会推荐std::set
而不是std::vector
. 使用这个:
std::find(vec.begin(), vec.end(), x)
runs in O(n) time, but std::set
has its own find()
member (ie. myset.find(x)
) which runs in O(log n) time - that's much more efficient with large numbers of elements
std::find(vec.begin(), vec.end(), x)
在 O(n) 时间内运行,但std::set
有自己的find()
成员(即myset.find(x)
),它在 O(log n) 时间内运行 - 对于大量元素来说效率更高
std::set
also guarantees all the added elements are unique, which saves you from having to do anything like if not contained then push_back()...
.
std::set
还保证所有添加的元素都是唯一的,这样您就不必执行诸如if not contained then push_back()...
.
回答by NeilDurant
See question: How to find an item in a std::vector?
请参阅问题:如何在 std::vector 中查找项目?
You'll also need to ensure you've implemented a suitable operator==()
for your object, if the default one isn't sufficient for a "deep" equality test.
您还需要确保您已经实现了一个适合operator==()
您的对象,如果默认一个不足以进行“深度”相等测试。