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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6277646/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 19:49:34  来源:igfitidea点击:

In C++ check if std::vector<string> contains a certain value

c++vectorstdstdvector

提问by Jame

Is there any built in function which tells me that my vector contains a certain element or not e.g.

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

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?

回答by Darhuuk

You can use std::findas follows:

您可以std::find按如下方式使用:

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

To be able to use std::find: include <algorithm>.

能够使用std::findinclude <algorithm>

回答by Alex B

  1. If your container only contains unique values, consider using std::setinstead. It allows querying of set membership with logarithmic complexity.

    std::set<std::string> s;
    s.insert("abc");
    s.insert("xyz");
    if (s.find("abc") != s.end()) { ...
    
  2. If your vector is kept sorted, use std::binary_search, it offers logarithmic complexity as well.

  3. If all else fails, fall back to std::find, which is a simple linear search.

  1. 如果您的容器仅包含唯一值,请考虑std::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,这是一个简单的线性搜索。

回答by colddie

In C++11, you can use std::any_ofinstead.

在 C++11 中,您可以std::any_of改为使用。

An example to find if there is any zero in the array:

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

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...";

回答by Nim

it's in <algorithm>and called std::find.

它在<algorithm>并被称为std::find

回答by Oliver Charlesworth