我要做的就是检查向量中是否存在一个元素,这样我就可以处理每一种情况。

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

当前回答

使用stl算法头中的find。我已经用int类型说明了它的用法。你可以使用任何你喜欢的类型,只要你可以比较相等(重载==如果你需要你的自定义类)。

#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;
}

其他回答

正如其他人所说,使用STL的find或find_if函数。但是如果你搜索的是非常大的向量,这会影响性能,你可能想要对你的向量排序,然后使用binary_search、lower_bound或upper_bound算法。

我用这样的东西…

#include <algorithm>


template <typename T> 
const bool Contains( std::vector<T>& Vec, const T& Element ) 
{
    if (std::find(Vec.begin(), Vec.end(), Element) != Vec.end())
        return true;

    return false;
}

if (Contains(vector,item))
   blah
else
   blah

...这样,它实际上是清晰可读的。 (显然,您可以在多个地方重用模板)。

template <typename T> bool IsInVector(const T & what, const std::vector<T> & vec)
{
    return std::find(vec.begin(),vec.end(),what)!=vec.end();
}

如果你的向量是无序的,使用MSN建议的方法:

if(std::find(vector.begin(), vector.end(), item)!=vector.end()){
      // Found the item
}

如果你的向量是有序的,使用binary_search方法Brian Neal建议:

if(binary_search(vector.begin(), vector.end(), item)){
     // Found the item
}

二分搜索的最差情况性能为O(log n),这比第一种方法更有效。为了使用二分搜索,您可以使用qsort首先对向量排序,以确保它是有序的。

你可以使用std::find from <algorithm>:

#include <algorithm>
#include <vector>
vector<int> vec; 
//can have other data types instead of int but must same datatype as item 
std::find(vec.begin(), vec.end(), item) != vec.end()

这将返回找到的第一个元素的迭代器。如果不存在,则返回一个指向倒数一的迭代器。用你的例子:

#include <algorithm>
#include <vector>

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