我要做的就是检查向量中是否存在某个元素,因此我可以处理每种情况。
if ( item_present )
do_this();
else
do_that();
#1楼
您可以尝试以下代码:
#include
#include
// You can use class, struct or primitive data type for Item
struct Item {
//Some fields
};
typedef std::vector ItemVector;
typedef ItemVector::iterator ItemIterator;
//...
ItemVector vtItem;
//... (init data for vtItem)
Item itemToFind;
//...
ItemIterator itemItr;
itemItr = std::find(vtItem.begin(), vtItem.end(), itemToFind);
if (itemItr != vtItem.end()) {
// Item found
// doThis()
}
else {
// Item not found
// doThat()
}
#2楼
如果没有订购您的向量,请使用建议的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首先对向量进行排序以确保其排序。
#3楼
如果您想在向量中找到一个字符串:
struct isEqual
{
isEqual(const std::string& s): m_s(s)
{}
bool operator()(OIDV* l)
{
return l->oid == m_s;
}
std::string m_s;
};
struct OIDV
{
string oid;
//else
};
VecOidv::iterator itFind=find_if(vecOidv.begin(),vecOidv.end(),isEqual(szTmp));
#4楼
我用这样的东西...
#include
template
const bool Contains( std::vector& 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
...那样实际上是清晰易读的。 (显然,您可以在多个地方重复使用模板)。
#5楼
template bool IsInVector(T what, std::vector * vec)
{
if(std::find(vec->begin(),vec->end(),what)!=vec->end())
return true;
return false;
}