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;
}
總結
以上是生活随笔為你收集整理的JAVA中vector是否存在数据_如何找出std :: vector中是否存在项目?的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 我的原创,思考写作时间在1小时以上,希望
- 下一篇: python笨办法_笨办法学Python