Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the time complexity of getting the max key of a std::map in C++?

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.

like image 351
Dun Peal Avatar asked Nov 02 '18 16:11

Dun Peal


People also ask

What is the complexity of std::map :: insert () method?

Time complexity: k*log(n) where n is size of map, k is no. of elements inserted.

What is time complexity of map in C++?

The time complexity of map operations is O(log n) while for unordered_map, it is O(1) on average.

What is the time complexity of the find () method of the std::map container?

The time complexity for searching elements in std::map is O(log n).

How do you find the maximum element on a map?

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.


1 Answers

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, while std::prev(c.end()) does.

like image 73
gsamaras Avatar answered Sep 21 '22 17:09

gsamaras