我要做的就是检查向量中是否存在一个元素,这样我就可以处理每一种情况。
if ( item_present )
do_this();
else
do_that();
我要做的就是检查向量中是否存在一个元素,这样我就可以处理每一种情况。
if ( item_present )
do_this();
else
do_that();
当前回答
template <typename T> bool IsInVector(const T & what, const std::vector<T> & vec)
{
return std::find(vec.begin(),vec.end(),what)!=vec.end();
}
其他回答
正如其他人所说,使用STL的find或find_if函数。但是如果你搜索的是非常大的向量,这会影响性能,你可能想要对你的向量排序,然后使用binary_search、lower_bound或upper_bound算法。
使用STL的find函数。
请记住,还有一个find_if函数,如果你的搜索更复杂,你可以使用它,例如,如果你不只是寻找一个元素,而是想看看是否有一个元素满足某个条件,例如,一个以“abc”开头的字符串。(find_if会给你一个指向第一个这样的元素的迭代器)。
下面是一个适用于任何容器的函数:
template <class Container>
const bool contains(const Container& container, const typename Container::value_type& element)
{
return std::find(container.begin(), container.end(), element) != container.end();
}
注意,您可以使用一个模板形参,因为您可以从Container中提取value_type。您需要typename,因为Container::value_type是一个依赖名称。
你也可以使用count。 它将返回向量中存在的项的数量。
int t=count(vec.begin(),vec.end(),item);
使用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;
}