日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

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

發布時間:2024/7/23 编程问答 27 豆豆
生活随笔 收集整理的這篇文章主要介紹了 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中是否存在项目?的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。