<algorithm>
中有什么东西允许你检查std :: container是否包含某些内容?或者,制作一个方法,例如:
if(a.x == b.x && a.y == b.y)
return true;
return false;
这只能用std::map
来完成,因为它使用密钥吗?
由于
答案 0 :(得分:451)
检查v
是否包含元素x
:
#include <algorithm>
if(std::find(v.begin(), v.end(), x) != v.end()) {
/* v contains x */
} else {
/* v does not contain x */
}
检查v
是否包含元素(非空):
if(!v.empty()){
/* v is non-empty */
} else {
/* v is empty */
}
答案 1 :(得分:88)
如果搜索元素很重要,我建议使用std::set
代替std::vector
。使用这个:
std::find(vec.begin(), vec.end(), x)
在O(n)时间运行,但std::set
有自己的find()
成员(即myset.find(x)
),它在O(log n)时间内运行 - 这对于大量元素来说效率更高
std::set
还保证所有添加的元素都是唯一的,这样您就无需执行if not contained then push_back()...
之类的操作。
答案 2 :(得分:11)
请参阅问题:How to find an item in a std::vector?
如果默认值不足以进行“深度”相等测试,您还需要确保为对象实现了合适的operator==()
。