可能重复:
如何在std :: vector中查找项目?
有什么东西<algorithm>可以让你检查std :: container是否包含某些内容?或者,制作一个方法,例如:
if(a.x == b.x && a.y == b.y)
return true;
return false;
Run Code Online (Sandbox Code Playgroud)
这可以只std::map使用密钥吗?
谢谢
You*_*You 485
检查是否v包含元素x:
#include <algorithm>
if(std::find(v.begin(), v.end(), x) != v.end()) {
/* v contains x */
} else {
/* v does not contain x */
}
Run Code Online (Sandbox Code Playgroud)
检查是否v包含元素(非空):
if(!v.empty()){
/* v is non-empty */
} else {
/* v is empty */
}
Run Code Online (Sandbox Code Playgroud)
Ash*_*ain 94
如果搜索元素很重要,我建议std::set不要使用std::vector.使用这个:
std::find(vec.begin(), vec.end(), x)在O(n)时间运行,但std::set有自己的find()成员(即.myset.find(x))在O(log n)时间运行 - 这对于大量元素来说效率更高
std::set还保证所有添加的元素都是独一无二的,这使您不必再做任何事情if not contained then push_back()....