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

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

The method m.rbegin();

Maps (and sets) are sorted, so the first element is the smallest, and the last element is the largest. By default maps use std::less, but you can switch the comparer and this would of course change the position of the largest element. (For example, using std::greater would place it at begin().

Keep in mind rbegin returns an iterator. To get the actual key, use m.rbegin()->first. You might wrap it up into a function for clarity, though I"m not sure if it’s worth it:

template <typename T>
inline const typename T::key_type& last_key(const T& pMap) {
    return pMap.rbegin()->first;
}

typedef std::map</* types */> map_type;

map_type myMap;
// populate

map_type::key_type k = last_key(myMap);

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、myMap.rbegin()

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

2、--myMap.end()

largestElement = (--myMap.end())->first; // end(): returns an iterator pointing to the theortical element following the last element 
int main() {
    std::map<int, string> mymap;
    mymap[1] = "a";
    mymap[2] = "hello";
    mymap[3] = "how r you";
    mymap[4] = "hi";

    for (auto i = mymap.begin(); i != mymap.end(); i++) {
        cout << i->first<< " ";
        cout << i->second << "\n";
    }

    cout << "test1\n";
    cout << mymap.rbegin()->first<< " ";
    cout << mymap.rbegin()->second<< " \n";

    cout << "test2\n";
    cout << (--mymap.end())->first<< " ";
    cout << (--mymap.end())->second<< " \n";
    return 0;
}
1 a
2 hello
3 how r you
4 hi
test1
4 hi 
test2
4 hi
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值