What's the most efficient way to check whether an stl vector of strings contains a spec开发者_如何转开发ific string?
The obvious yet possibly too-slow solution is std::find(vec.begin(), vec.end(), your_string);
If your vector isn't changing much, sort it first, then use binary_search
, lower_bound
, upper_bound
, or equal_range
. If your vector changes a lot, consider using a set
/multiset
(or if needed map
/multimap
) instead.
Depending on your needs a hash (unordered_set
) might be appropriate as well, but it's more different from your initial container choice than normal ordered containers, and not supplied prior to C++0x (you can get it from boost easily).
Use std::find
to find the target string. This is a linear search, so beware searching large vectors.
To find out if the vector contains the target or not, use:
bool isPresent = (std::find(vec.begin(), vec.end(), target) != vec.end());
Here is a C++11 alternative:
#include<functional>
#include<vector>
#include<string>
std::vector<std::string> v;
bool elementFound = std::any_of(v.begin(), v.end(), [](std::string const& s) {return s=="string-to-search";});
Feel free to adjust the lambda function to what you want, e.g.
[](std::string const& s) {return s.size()>3;}
vector<string> v;
vector<string>::iterator it;
it = std::find(v.begin(), v.end(), "stringToFind");
Use std::find to find the string.
std::find(stringVector.begin(), stringVector.end(), "specificStringToFind") ;
精彩评论