2010-07-14 60 views
12

可能重复:
How to find an item in a std::vector?如何在一个句子中检查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 
    } 
} 

换句话说,我正在寻找一个短期和简单的语法验证向量中元素的存在。我不想为这个向量引入另一个临时变量。谢谢!

回答

6
int elem = 42; 
std::vector<int> v; 
v.push_back(elem); 
if(std::find(v.begin(), v.end(), elem) != v.end()) 
{ 
    //elem exists in the vector 
} 
26

未排序矢量:

if (std::find(v.begin(), v.end(),value)!=v.end()) 
    ... 

排序矢量:

if (std::binary_search(v.begin(), v.end(), value) 
    ... 

P.S.可能需要包括<algorithm>

+1

+1的P.S.,我从各种渠道上面的代码,但不知道包含头,因此我的代码是给错误。谢谢。 – 2015-01-24 20:25:27

1

尝试std::find

vector<int>::iterator it = std::find(v.begin(), v.end(), 123); 

if(it==v.end()){ 

    std::cout<<"Element not found"; 
} 
+2

当然if()条件应该是!=? – JBRWilkinson 2010-07-14 14:09:07

+0

是的!编辑.... – 2010-07-14 14:10:15

相关问题