我要做的就是检查向量中是否存在一个元素,这样我就可以处理每一种情况。
if ( item_present )
do_this();
else
do_that();
我要做的就是检查向量中是否存在一个元素,这样我就可以处理每一种情况。
if ( item_present )
do_this();
else
do_that();
当前回答
正如其他人所说,使用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
...这样,它实际上是清晰可读的。 (显然,您可以在多个地方重用模板)。
使用STL的find函数。
请记住,还有一个find_if函数,如果你的搜索更复杂,你可以使用它,例如,如果你不只是寻找一个元素,而是想看看是否有一个元素满足某个条件,例如,一个以“abc”开头的字符串。(find_if会给你一个指向第一个这样的元素的迭代器)。
boost可以使用any_of_equal:
#include <boost/algorithm/cxx11/any_of.hpp>
bool item_present = boost::algorithm::any_of_equal(vector, element);
你可以使用find函数,在std命名空间中找到,即std::find。向std::find函数传递要搜索的向量的begin迭代器和end迭代器,以及要查找的元素,并将结果迭代器与向量的结束迭代器进行比较,以查看它们是否匹配。
std::find(vector.begin(), vector.end(), item) != vector.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首先对向量排序,以确保它是有序的。