在 C++ 中检查 std::vector<string> 是否包含某个值[重复]

问题描述 投票:0回答:5

是否有任何内置函数告诉我我的向量是否包含某个元素 例如

std::vector<string> v;
v.push_back("abc");
v.push_back("xyz");

if (v.contains("abc")) // I am looking for one such feature, is there any
                       // such function or i need to loop through whole vector?
c++ vector std stdvector
5个回答
230
投票

您可以使用

std::find
,如下所示:

if (std::find(v.begin(), v.end(), "abc") != v.end())
{
  // Element in vector.
}

为了能够使用

std::find
include <algorithm>


43
投票
  1. 如果您的容器仅包含唯一值,请考虑使用

    std::set
    代替。它允许以对数复杂度查询集合成员资格。

     #include <set>
    
     std::set<std::string> s;
     s.insert("abc");
     s.insert("xyz");
     if (s.find("abc") != s.end()) { ...
    
  2. 如果你的向量保持排序,请使用

    std::binary_search
    ,它也提供对数复杂度。

  3. 如果所有其他方法都失败,请退回到

    std::find
    ,这是一个简单的线性搜索。


24
投票

在 C++11 中,您可以使用

std::any_of
代替。

查找数组中是否有零的示例:

std::array<int,3> foo = {0,1,-1};
if ( std::any_of(foo.begin(), foo.end(), [](int i){return i==0;}) )
std::cout << "zero found...";

6
投票

它在

<algorithm>
中,名为
std::find


3
投票
© www.soinside.com 2019 - 2024. All rights reserved.