我有一个字符串前缀数组:std::vector<std::string> haystack = {"/bin/", "/usr/bin/", "/usr/local/bin/"}
。C++:高效地在子字符串数组中找到一个字符串
有没有一种有效的方法来找到std::string needle = "/bin/echo"
开头的子字符串从haystack
,使用标准的C++库?
如果我需要找到完全匹配,我可以使用std::set<std::string>
,这将执行一个有效的二进制搜索,但是我只需要匹配字符串的第一部分,所以目前我正在使用一个简单的循环:
for (auto it = haystack.begin(); it != haystack.end(); it++) {
if (needle.compare(0, it->size(), *it) == 0) {
return true; // Found it
}
}
return false;
请定义_efficient_。为了缩短代码,有'std :: find_if()'。 –
比遍历整个'haystack'数组更快,这将是'O(n)'。 'find_if'将执行与'O(n)'速度完全相同的循环。 – pelya
分而治之。但即使这样也不能保证比O(n)更快。 –