如果您有一个未排序的容器,时间复杂度最好也只能是
O(n),这意味着以线性方式(例如使用 for 循环)遍历整个容器。如果您的容器已经排好序(例如使用
std::set
而不是
std::vector
),则可以获得更好的时间复杂度
O(log n),这意味着可以使用二分查找等方法进行搜索。
在 C++17 之前,我无法想到比您的解决方案更好的方法(因为通过
std::string::substr
创建子字符串会不必要地复制子字符串)。然而,C++17 引入了
std::string_view
,它不会进行任何复制。启用编译器优化后,应该没有明显的性能差异。
std::vector<std::string> v { "abcd", "abcdefg", "aaaabbbb", "abc", "ab"};
std::string_view query = "abc";
for (auto const& str : v)
{
if (str.size() < query.size())
continue;
auto probe = std::string_view(str).substr(0, query.size());
if (query == probe)
std::cout << "Item found: " << str << "\n";
}
实时示例
以下是使用std::set
快速搜索的版本:
std::set<std::string> v { "abcd", "abcdefg", "aaaabbbb", "abc", "ab"};
std::string query = "abc";
for (auto it = v.lower_bound(query); it != v.end(); ++it)
{
auto probe = std::string_view(*it).substr(0, query.size());
if (query == probe)
std::cout << "Item found: " << *it << "\n";
else
break;
}
实时例子
(此链接为实时代码演示)
if ( v[i].substr(0, substring.size()) == substring ) { /* ... */ }
。 - DimChtz