Is there a nice and simple way to find nth element
in C++
std::map
? Particularly I'm looking for an algorithm to erase the last k
elements from the map
. That would make sense to retrieve the iterator to the nth element
and call std::map::erase
. The requirement is that complexity doesn't suffer - that should be possible to erase the element range in O(N)
.
Copy of the data shouldn't be made just to erase the elements. For example one solution is to copy the data into std::vector
, then do std::nth_element
on std::vector
, and then std::map::find
to find the iterator in order to find out where to erase from.
One of other solutions is to just iterate over std::map
maintaining a counter variable on the number of elements to remove. That would give O(n)
. Is that possible to replace the for
loop with STL algorithm
?