Are std::find
and std::map.find
both O(logN)?
If they are, how does std::find
implement search over std::map
in logarithmic time?
Is the implementation of std::find
specialized for the std::map
use case?
The time complexity for searching elements in std::map is O(log n).
Yes, indeed std::map will be O(log N) and std::unordered_map will have average constant-time complexity and O(N) in the worst case if there are too many hash collisions. Expected O(1) . It is fairly easy to build a degenerate case where it is O(N) .
std::map is a sorted associative container that contains key-value pairs with unique keys. Keys are sorted by using the comparison function Compare . Search, removal, and insertion operations have logarithmic complexity. Maps are usually implemented as red-black trees.
No, std::find
is O(N), regardless of the container. It doesn't know the "container", there is no specialization for std::map
. std::find
uses only the iterators, which do not have information about the underlying container. According to cppreference.com, the implementation is equivalent to:
template<class InputIt, class T>
InputIt find(InputIt first, InputIt last, const T& value)
{
for (; first != last; ++first) {
if (*first == value) {
return first;
}
}
return last;
}
According to the C++ standard (emphasize mine):
25.2.5 Find [alg.find]
template<class InputIterator, class T>
InputIterator find(InputIterator first, InputIterator last,
const T& value);
...
Returns: The first iterator i
in the range [first,last)
for which the following corresponding conditions hold: *i == value
, . . . . Returns last
if no such iterator is found.
Complexity: At most last - first applications of the corresponding predicate.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With