Possible Duplicate:
How to find an item in a std::vector?
这就是我要找的:
#include <vector>
std::vector<int> foo() {
// to create and return a vector
return std::vector<int>();
}
void bar() {
if (foo().has(123)) { // it's not possible now, but how?
// do something
}
}
换句话说,我正在寻找一种简短的语法来验证 vector 中元素的存在。而且我不想为这个 vector 引入另一个临时变量。谢谢!
最佳答案
未排序的 vector :
if (std::find(v.begin(), v.end(),value)!=v.end())
...
排序 vector :
if (std::binary_search(v.begin(), v.end(), value)
...
附:可能需要包含<algorithm>
标题
关于c++ - 如何在一行中检查 std::vector 中是否存在元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3246863/