In C++ check if std::vector<string> contains a certain value [duplicate]
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 1:
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:
-
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()) { ...
-
If your vector is kept sorted, use
std::binary_search
, it offers logarithmic complexity as well. -
If all else fails, fall back to
std::find
, which is a simple linear search.