I've got an array of string prefixes: std::vector<std::string> haystack = {"/bin/", "/usr/bin/", "/usr/local/bin/"}
.
Is there an efficient way to find that a std::string needle = "/bin/echo"
starts with a sub-string from haystack
, using standard C++ library?
If I would need to find the exact match, I could use std::set<std::string>
, which would perform an efficient binary search, however I need to match only the first part of the string, so currently I'm doing it using a simple loop:
for (auto it = haystack.begin(); it != haystack.end(); it++) {
if (needle.compare(0, it->size(), *it) == 0) {
return true; // Found it
}
}
return false;