Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

check if a std::vector contains a certain object? [duplicate]

Tags:

c++

vector

Is there something in <algorithm> which allows you to check if a std:: container contains something? Or, a way to make one, for example:

if(a.x == b.x && a.y == b.y) return true;  return false; 

Can this only be done with std::map since it uses keys?

Thanks

like image 675
jmasterx Avatar asked Aug 10 '10 15:08

jmasterx


People also ask

How do you check if a vector contains an element?

We can find the index of an element in a vector using the std::find_if() function. This function finds the first element in a range for which the predicate function returns true.

Can vector have duplicates in C++?

The idea is to insert all vector elements in a set and copy the set's contents back again into the vector. This works as inserting elements into the set removes all duplicates as all set elements must be distinct. Please note that this might change the original ordering of elements in the vector.


2 Answers

Checking if v contains the element x:

#include <algorithm>  if(std::find(v.begin(), v.end(), x) != v.end()) {     /* v contains x */ } else {     /* v does not contain x */ } 

Checking if v contains elements (is non-empty):

if(!v.empty()){     /* v is non-empty */ } else {     /* v is empty */ } 
like image 85
You Avatar answered Oct 10 '22 01:10

You


If searching for an element is important, I'd recommend std::set instead of std::vector. Using this:

std::find(vec.begin(), vec.end(), x) runs in O(n) time, but std::set has its own find() member (ie. myset.find(x)) which runs in O(log n) time - that's much more efficient with large numbers of elements

std::set also guarantees all the added elements are unique, which saves you from having to do anything like if not contained then push_back()....

like image 25
AshleysBrain Avatar answered Oct 10 '22 01:10

AshleysBrain