How can I check for existence of element in std::vector, in one sentence?
本问题已经有最佳答案,请猛点这里访问。
Possible Duplicate:
How to find an item in a std::vector?
这就是我正在寻找的:
1 2 3 4 5 6 7 8 9 10 | #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 } } |
换句话说,我正在寻找一个简短的语法来验证向量中元素的存在。我不想为这个向量引入另一个临时变量。谢谢!
未排序向量:
1 2 | if (std::find(v.begin(), v.end(),value)!=v.end()) ... |
排序向量:
1 2 | if (std::binary_search(v.begin(), v.end(), value) ... |
P.S.可能需要包括
1 2 3 4 5 6 7 | 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 } |
试试
1 2 3 4 5 6 | vector<int>::iterator it = std::find(v.begin(), v.end(), 123); if(it==v.end()){ std::cout<<"Element not found"; } |