Take the 2-minute tour ×

This question already has an answer here:

Is there any built in function which tells me that my vector contains a certain element or not e.g.

std::vector<string> v;

if (v.contains("abc")) // I am looking for one such feature, is there any
                       // such function or i need to loop through whole vector?
share|improve this question
add comment

marked as duplicate by jogojapan, PlasmaHH, Wooble, zessx, nalply Feb 27 '13 at 13:48


5 Answers

up vote 39 down vote accepted

You can use std::find as follows:

if (std::find(v.begin(), v.end(), "abc") != v.end())
  // Element in vector.

To be able to use std::find: include <algorithm>.

share|improve this answer
add comment

it's in <algorithm> and called std::find.

share|improve this answer
add comment
  1. If your container only contains unique values, consider using std::set instead. It allows querying of set membership with logarithmic complexity.

    std::set<std::string> s;
    if (s.find("abc") != s.end()) { ...
  2. If your vector is kept sorted, use std::binary_search, it offers logarithmic complexity as well.

  3. If all else fails, fall back to std::find, which is a simple linear search.

share|improve this answer
Even better, if you don't need an ordering on the strings, use a std::tr1::unordered_set<std::string>, available from <tr1/unordered_set> or <unordered_set>, which has (almost) constant lookup and query time. With either set or unordered_set you can alternatively say if (s.count("abc")). Don't forget to accept one of the answers. –  Kerrek SB Jun 8 '11 at 11:05
add comment


share|improve this answer
add comment

In C++11, you can use std::any_of instead.

share|improve this answer
add comment
