Given two std::set
s, one can simply iterate through both sets simultaneously and compare the elements, resulting in linear complexity. This doesn't work for std::unordered_set
s, because the elements may be stored in any order. So how expensive is a == b
for std::unordered_set
?
相关问题
- Sorting 3 numbers without branching [closed]
- How to compile C++ code in GDB?
- Why does const allow implicit conversion of refere
- thread_local variables initialization
- What uses more memory in c++? An 2 ints or 2 funct
相关文章
- C#中 public virtual string Category { get; }这么写会报错:
- Class layout in C++: Why are members sometimes ord
- What is the complexity of bisect algorithm?
- How to mock methods return object with deleted cop
- Which is the best way to multiply a large and spar
- C++ default constructor does not initialize pointe
- Selecting only the first few characters in a strin
- What exactly do pointers store? (C++)
Complexity of
operator==
andoperator!=
:Linear complexity in the average case. N2 in the worst case, where N is the size of the container.
More details in the standard §23.2.5, point 11:
For
unordered_set
andunordered_map
, the complexity ofoperator==
(i.e., the number of calls to the==
operator of thevalue_type
, to the predicate returned bykey_equal()
, and to the hasher returned byhash_function()
) is proportional toN
in the average case and to N2 in the worst case, whereN
isa.size()
.The very worst case is O(n²).
But unordered sets are in fact ordered by hash. So it is possible to compare the hashes (if this fails the sets cannot be equal) and then verify that same hashes (linear) have real same values (O(n²) for different values with the same hash) behind.
In the best case this is O(n).
Normally the complexity tends to O(n) if the hash function is "good" (different objects -> always different hash) and to O(n²) if the hash function is "bad" (everything always has the same hash value)