http://www.cplusplus.com/reference/unordered_set/unordered_set/find/
对于 unordered_set,unordered_set 中 find 的时间复杂度平均为常数。
如果我有一个 unordered_set 字符串,那么在该集合中查找字符串的时间复杂度是多少?
它是常量还是 O(字符串的长度)?
最佳答案
std::unordered_set
被实现为一个哈希表。它的 find
方法的平均情况复杂度为 O(1)
和最坏情况下的复杂性 O(set.size())
[tab:container.hash.req] 指定的键比较.
默认情况下,std::unordered_set<std::string>
用途 operator==
比较键,所以每个键比较在 O(str.size())
中运行如 [string.view.ops] 中所述( operator==(const std::string&, const std::string&)
定义为等价于 std::string_view(str1) == std::string_view(str2)
,后者定义为等价于 std::string_view(str1).compare(std::string_view(str2) == 0
)。
对于 std::unordered_set<std::string>
,容器必须计算要查找的字符串的哈希值。默认情况下,它使用 std::hash<std::string>
为了这。该标准没有为 std::hash<std::string>
指定任何复杂性要求。 ,但很可能是 O(str.size())
.
关于c++ - 在无序字符串集中查找字符串的时间复杂度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61284351/