C++ How to find the biggest key in a std::map?

后端 未结 4 1003
走了就别回头了
走了就别回头了 2020-12-14 00:00

At the moment my solution is to iterate through the map to solve this.

I see there is a upper_bound method which can make this loop faster, but is there

4条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-14 00:41

    Since the map is just an AVL tree then, it's sorted -in an ascending order-. So, the element with largest key is the last element and you can obtain it using one of the following two methods:

    1.

        largestElement = (myMap.rbegin())-> first; // rbegin(): returns an iterator pointing to the last element
    
    1.  largestElement = (--myMap.end())->first; // end(): returns an iterator pointing to the theortical element following the last element 
      

提交回复
热议问题