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

Jam*_*ame 67 c++ vector std stdvector

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

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?
Run Code Online (Sandbox Code Playgroud)

Dar*_*uuk 158

您可以使用std::find如下:

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

能够使用std::find:include <algorithm>.


Ale*_*x B 29

  1. 如果您的容器仅包含唯一值,请考虑使用std::set.它允许以对数复杂度查询集合成员资格.

    std::set<std::string> s;
    s.insert("abc");
    s.insert("xyz");
    if (s.find("abc") != s.end()) { ...
    
    Run Code Online (Sandbox Code Playgroud)
  2. 如果您的矢量保持排序,使用std::binary_search,它也提供对数复杂性.

  3. 如果所有其他方法都失败了,请回到std::find,这是一个简单的线性搜索.

  • 更好的是,如果您不需要对字符串进行排序,请使用`std :: tr1 :: unordered_set <std :: string>`,可从`<tr1/unordered_set>`或`<unordered_set>`获得,具有(几乎)不断的查找和查询时间.使用set或unordered_set,您也可以说`if(s.count("abc"))`.别忘了_accept_其中一个答案. (3认同)

col*_*die 16

在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...";
Run Code Online (Sandbox Code Playgroud)

  • @Xam谢谢.我知道如何使用`any_of`,我鼓励colddie改进答案 (3认同)

Nim*_*Nim 5

它在里面<algorithm>并称为std::find


归档时间:

查看次数:

160200 次

最近记录:

6 年,11 月 前