I'm trying to find the largest value in a std::map
, which would be the last node in the tree (since std::map
keys are sorted).
Cppref says std::map.end()
is constant time. But to get the largest key, I must get the previous value of this iterator, i.e. *std::prev(std::map.end())
.
What's the time complexity of that operation?
I understand that this should equivalent to --std::map.end()
, but I don't know the cost of that operation either.
Time complexity: k*log(n) where n is size of map, k is no. of elements inserted.
The time complexity of map operations is O(log n) while for unordered_map, it is O(1) on average.
The time complexity for searching elements in std::map is O(log n).
The recommended solution is to use the std::max_element to find an element having the maximum value in a map. It returns an iterator pointing to an element with the maximum value in the specified range. It is defined in the <algorithm> header.
Use an std::map::rbegin()
instead, which:
Returns a reverse iterator pointing to the last element in the container (i.e., its reverse beginning).
and:
Complexity
Constant.
where the last word should sound like music in your ears.
std::prev(std::map.end())
is constant in complexity.
Moreover, your understanding about the equivalency is wrong.
From std::prev
notes:
Although the expression
--c.end()
often compiles, it is not guaranteed to do so:c.end()
is an rvalue expression, and there is no iterator requirement that specifies that decrement of an rvalue is guaranteed to work. In particular, when iterators are implemented as pointers,--c.end()
does not compile, whilestd::prev(c.end())
does.
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