亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何確定一個項目是否存在于STD:向量中?

如何確定一個項目是否存在于STD:向量中?

C++
幕布斯7119047 2019-06-27 16:24:34
如何確定一個項目是否存在于STD:向量中?我所要做的就是檢查向量中是否存在一個元素,這樣我就可以處理每一種情況。if ( item_present )    do_this();else    do_that();
查看完整描述

3 回答

?
ITMISS

TA貢獻1871條經驗 獲得超8個贊

你可以用std::find從…<algorithm>:

#include <vector>vector<int> vec; //can have other data types instead of int but must same datatype as item std::find(vec.begin(), vec.end(), item) != vec.end()

這會返回一個bool(true如果有,false否則)。以你為例:

#include <algorithm>#include <vector>if ( std::find(vec.begin(), vec.end(), item) != vec.end() )
   do_this();else
   do_that();


查看完整回答
反對 回復 2019-06-27
?
互換的青春

TA貢獻1797條經驗 獲得超6個贊

正如其他人所說,使用STLfindfind_if職能。但是,如果在非常大的向量中搜索,這會影響性能,則可能需要對向量進行排序,然后使用binary_searchlower_bound,或upper_bound算法。


查看完整回答
反對 回復 2019-06-27
?
牛魔王的故事

TA貢獻1830條經驗 獲得超3個贊

在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;}


查看完整回答
反對 回復 2019-06-27
  • 3 回答
  • 0 關注
  • 606 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號