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
如果您的容器仅包含唯一值,请考虑使用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)如果您的矢量保持排序,使用std::binary_search,它也提供对数复杂性.
如果所有其他方法都失败了,请回到std::find,这是一个简单的线性搜索.
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)
| 归档时间: |
|
| 查看次数: |
160200 次 |
| 最近记录: |