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

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

当前回答

我个人最近使用模板一次处理多种类型的容器,而不是只处理向量。我在网上找到了一个类似的例子(不记得在哪里了),所以功劳归于我从谁那里偷来的。这种特殊的模式似乎也可以处理原始数组。

template <typename Container, typename T = typename std::decay<decltype(*std::begin(std::declval<Container>()))>::type>
bool contains(Container && c, T v)
{
    return std::find(std::begin(c), std::end(c), v) != std::end(c);
}

其他回答

我用这样的东西…

#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

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

boost可以使用any_of_equal:

#include <boost/algorithm/cxx11/any_of.hpp>

bool item_present = boost::algorithm::any_of_equal(vector, element);

使用STL的find函数。

请记住,还有一个find_if函数,如果你的搜索更复杂,你可以使用它,例如,如果你不只是寻找一个元素,而是想看看是否有一个元素满足某个条件,例如,一个以“abc”开头的字符串。(find_if会给你一个指向第一个这样的元素的迭代器)。

你也可以使用count。 它将返回向量中存在的项的数量。

int t=count(vec.begin(),vec.end(),item);

记住,如果你要做大量的查找,有STL容器会更好。我不知道你的应用程序是什么,但是像std::map这样的关联容器可能值得考虑。

vector是容器的选择,除非您有其他原因,按值查找就是这样一个原因。