JAVA中vector是否存在数据_如何找出std :: vector中是否存在项目?

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

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;

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值