In C++ check if std::vector<string> contains a certain value

Jame picture Jame · Jun 8, 2011 · Viewed 196.8k times · Source

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

std::vector<string> v;
v.push_back("abc");
v.push_back("xyz");

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

Answer

Darhuuk picture Darhuuk · Jun 8, 2011

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>.