在 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
In C++ check if std::vector<string> contains a certain value
提问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
回答by Alex B
If your container only contains unique values, consider using
std::set
instead. 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()) { ...
If your vector is kept sorted, use
std::binary_search
, it offers logarithmic complexity as well.If all else fails, fall back to
std::find
, which is a simple linear search.
如果您的容器仅包含唯一值,请考虑
std::set
改用。它允许查询具有对数复杂度的集合成员资格。std::set<std::string> s; s.insert("abc"); s.insert("xyz"); if (s.find("abc") != s.end()) { ...
如果您的向量保持排序,请使用
std::binary_search
,它也提供对数复杂度。如果所有其他方法都失败了,请回退到
std::find
,这是一个简单的线性搜索。
回答by colddie
In C++11, you can use std::any_of
instead.
在 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
。