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

2018-12-31 08:08发布

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();

标签: c++ vector std
17条回答
不流泪的眼
2楼-- · 2018-12-31 09:03

You can use the find function, found in the std namespace, ie std::find. You pass the std::find function the begin and end iterator from the vector you want to search, along with the element you're looking for and compare the resulting iterator to the end of the vector to see if they match or not.

std::find(vector.begin(), vector.end(), item) != vector.end()

You're also able to dereference that iterator and use it as normal, like any other iterator.

查看更多
笑指拈花
3楼-- · 2018-12-31 09:05

You can try this code:

#include <algorithm>
#include <vector>

// You can use class, struct or primitive data type for Item
struct Item {
    //Some fields
};
typedef std::vector<Item> 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()
}
查看更多
若你有天会懂
4楼-- · 2018-12-31 09:05

You can use count too. It will return the number of items present in a vector.

int t=count(vec.begin(),vec.end(),item);
查看更多
骚的不知所云
5楼-- · 2018-12-31 09:05

Using Newton C++ it's easier, self-documented and faster than with std::find because of return a bool directly.

bool exists_linear( INPUT_ITERATOR first, INPUT_ITERATOR last, const T& value )

bool exists_binary( INPUT_ITERATOR first, INPUT_ITERATOR last, const T& value )

I think it's obvious what the functions do.

include <newton/algorithm/algorithm.hpp>

if ( newton::exists_linear(first, last, value) )
   do_this();
else
   do_that();
查看更多
深知你不懂我心
6楼-- · 2018-12-31 09:06

You can use std::find from <algorithm>:

std::find(vector.begin(), vector.end(), item) != vector.end()

This returns a bool (true if present, false otherwise). With your example:

#include <algorithm>

if ( std::find(vector.begin(), vector.end(), item) != vector.end() )
   do_this();
else
   do_that();
查看更多
登录 后发表回答