我要做的就是检查向量中是否存在一个元素,这样我就可以处理每一种情况。
if ( item_present )
do_this();
else
do_that();
我要做的就是检查向量中是否存在一个元素,这样我就可以处理每一种情况。
if ( item_present )
do_this();
else
do_that();
当前回答
你可以使用find函数,在std命名空间中找到,即std::find。向std::find函数传递要搜索的向量的begin迭代器和end迭代器,以及要查找的元素,并将结果迭代器与向量的结束迭代器进行比较,以查看它们是否匹配。
std::find(vector.begin(), vector.end(), item) != vector.end()
您还可以解除对该迭代器的引用,并像其他迭代器一样正常使用它。
其他回答
在c++ 11中,你可以使用any_of。例如,如果它是一个向量<字符串> v;然后:
if (any_of(v.begin(), v.end(), bind(equal_to<string>(), _1, item)))
do_this();
else
do_that();
或者,使用lambda:
if (any_of(v.begin(), v.end(), [&](const std::string& elem) { return elem == item; }))
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;
}
template <typename T> bool IsInVector(const T & what, const std::vector<T> & vec)
{
return std::find(vec.begin(),vec.end(),what)!=vec.end();
}
记住,如果你要做大量的查找,有STL容器会更好。我不知道你的应用程序是什么,但是像std::map这样的关联容器可能值得考虑。
vector是容器的选择,除非您有其他原因,按值查找就是这样一个原因。
你也可以使用count。 它将返回向量中存在的项的数量。
int t=count(vec.begin(),vec.end(),item);