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

C++VectorStdStdvector

C++ Problem Overview


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?

C++ Solutions


Solution 1 - C++

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

Solution 2 - C++

  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;
     s.insert("abc");
     s.insert("xyz");
     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.

Solution 3 - C++

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

An example to find if there is any zero in the array:

std::array<int,3> foo = {0,1,-1};
if ( std::any_of(foo.begin(), foo.end(), [](int i){return i==0;}) )
std::cout << "zero found...";

Solution 4 - C++

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

Solution 5 - C++

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJameView Question on Stackoverflow
Solution 1 - C++AVHView Answer on Stackoverflow
Solution 2 - C++Alex BView Answer on Stackoverflow
Solution 3 - C++colddieView Answer on Stackoverflow
Solution 4 - C++NimView Answer on Stackoverflow
Solution 5 - C++Oliver CharlesworthView Answer on Stackoverflow