Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I check for existence of element in std::vector, in one line? [duplicate]

Tags:

c++

vector

Possible Duplicate:
How to find an item in a std::vector?

This is what I'm looking for:

#include <vector> std::vector<int> foo() {   // to create and return a vector   return std::vector<int>(); } void bar() {   if (foo().has(123)) { // it's not possible now, but how?     // do something   } } 

In other words, I'm looking for a short and simple syntax to validate the existence of an element in a vector. And I don't want to introduce another temporary variable for this vector. Thanks!

like image 365
yegor256 Avatar asked Jul 14 '10 14:07

yegor256


People also ask

How do you check if a value already exists in a vector?

So, to check if an element exist in vector or not, we can pass the start & end iterators of vector as initial two arguments and as the third argument pass the value that we need to check. If element exists in the vector, then it will return the iterator pointing to that element.

Can std :: vector have duplicates?

Yes, but sorting a vector modifies the original content.


1 Answers

Unsorted vector:

if (std::find(v.begin(), v.end(),value)!=v.end())     ... 

Sorted vector:

if (std::binary_search(v.begin(), v.end(), value)    ... 

P.S. may need to include <algorithm> header

like image 172
Vladimir Avatar answered Oct 02 '22 21:10

Vladimir