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
Jame Jun 08 2018-11-11T00: 00Z
source share5 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
Darhuuk Jun 08 2018-11-11T00: 00Z
source share
If your container contains only unique values, use
std::setinstead. 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
Alex B Jun 08 '11 at 11:00 2011-06-08 11:00
source shareIn C ++ 11, you can use std :: any_of instead.
+10
colddie Feb 27 '13 at 3:34 am
source sharein <algorithm> and is called std::find .
+4
Nim Jun 08 2018-11-11T00: 00Z
source share