How to find out if an item is present in a std::vector?

我想要做的就是检查向量中是否存在元素,以便处理每个案例。

if ( item_present )
   do_this();
else
   do_that();

You can use std::find from <algorithm> :

std::find(vector.begin(), vector.end(), item) != vector.end()

This returns a bool ( true if present, false otherwise). With your example:

#include <algorithm>

if ( std::find(vector.begin(), vector.end(), item) != vector.end() )
   do_this();
else
   do_that();

As others have said, use the STL find or find_if functions. But if you are searching in very large vectors and this impacts performance, you may want to sort your vector and then use the binary_search , lower_bound , or upper_bound algorithms.


Use find from the algorithm header of stl.I've illustrated its use with int type. You can use any type you like as long as you can compare for equality (overload == if you need to for your custom class).

#include <algorithm>
#include <vector>

using namespace std;
int main()
{   
    typedef vector<int> IntContainer;
    typedef IntContainer::iterator IntIterator;

    IntContainer vw;

    //...

    // find 5
    IntIterator i = find(vw.begin(), vw.end(), 5);

    if (i != vw.end()) {
        // found it
    } else {
        // doesn't exist
    }

    return 0;
}
链接地址: http://www.djcxy.com/p/15056.html

上一篇: 无法在Lion下使用RVM安装Ruby - GCC问题

下一篇: 如何找出一个项目是否存在于std :: vector中?