How to find out if an item is present in a std::vector?

后端 未结 18 2524
滥情空心
滥情空心 2020-11-22 05:31

All I want to do is to check whether an element exists in the vector or not, so I can deal with each case.

if ( item_present )
   do_this();
else
   do_that(         


        
18条回答
  •  梦谈多话
    2020-11-22 06:05

    You can try this code:

    #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()
    }
    

提交回复
热议问题