Search code examples
c++vectorstdstdvector

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


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?

Solution

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