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

Is there a built-in function that tells me that my vector contains a specific element or not for example.

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? 
+46
c ++ vector std stdvector
Jun 08 2018-11-11T00:
source share
5 answers

You can use std::find as follows:

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

To use std::find : include <algorithm> .

+112
Jun 08 2018-11-11T00:
source share
— -
  • If your container contains only unique values, use std::set instead. It allows you to request a given membership with logarithmic complexity.

     std::set<std::string> s; s.insert("abc"); s.insert("xyz"); if (s.find("abc") != s.end()) { ... 
  • If your vector is sorted, use std::binary_search , it also offers logarithmic complexity.

  • If all else fails, return to std::find , which is a simple linear search.

+23
Jun 08 '11 at 11:00
source share

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

+10
Feb 27 '13 at 3:34
source share

in <algorithm> and is called std::find .

+4
Jun 08 2018-11-11T00:
source share
+3
Jun 08 2018-11-11T00:
source share



All Articles