首页 文章

检查std :: vector是否包含某个对象? [重复]

提问于
浏览
212

可能重复:如何在std :: vector中查找项目?

<algorithm> 中有什么东西可以让你检查std :: container是否包含某些东西?或者,制作一个方法,例如:

if(a.x == b.x && a.y == b.y)
return true;

return false;

这只能用 std::map 完成,因为它使用键吗?

谢谢

3 回答

  • 10

    检查 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 */
    }
    
  • 80

    如果搜索元素很重要,我建议使用 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()... 那样做任何事情 .

  • 424

    看问题:How to find an item in a std::vector?

    您'll also need to ensure you'已为您的对象实现了合适的 operator==() ,如果默认值不足以进行"deep"相等测试 .

相关问题