是否有任何内置函数告诉我我的向量是否包含某个元素 例如
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?
std::find
,如下所示:
if (std::find(v.begin(), v.end(), "abc") != v.end())
{
// Element in vector.
}
为了能够使用
std::find
:include <algorithm>
。
std::set
代替。它允许以对数复杂度查询集合成员资格。
#include <set>
std::set<std::string> s;
s.insert("abc");
s.insert("xyz");
if (s.find("abc") != s.end()) { ...
std::binary_search
,它也提供对数复杂度。
std::find
,这是一个简单的线性搜索。
在 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...";
它在
<algorithm>
中,名为 std::find
。