C++ 如何在 std::map 中找到最大的键?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1660195/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 20:48:15  来源:igfitidea点击:

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

c++stlmap

提问by gak

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

目前我的解决方案是遍历地图来解决这个问题。

I see there is a upper_boundmethod which can make this loop faster, but is there a quicker or more succinct way?

我看到有一种upper_bound方法可以使这个循环更快,但有没有更快或更简洁的方法?

回答by GManNickG

The end:

结束:

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::greaterwould place it at begin().

Maps(和sets)是有序的,所以第一个元素最小,最后一个元素最大。默认映射使用std::less,但您可以切换比较器,这当然会更改最大元素的位置。(例如, usingstd::greater会将它放在begin().

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

请记住rbegin返回一个迭代器。要获取实际密钥,请使用m.rbegin()->first. 为了清楚起见,您可能会将其包装成一个函数,但我不确定它是否值得:

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);

回答by user200783

The entries in a std::map are sorted, so for a std::map m (assuming m.empty()is false), you can get the biggest key easily: (--m.end())->first

std::map 中的条目已排序,因此对于 std::map m(假设m.empty()为 false),您可以轻松获得最大的键:(--m.end())->first

回答by Vivek

As std::map is assosiative array one can easily find biggest or smallest key very easily. By defualt compare function is less(<) operator so biggest key will be last element in map. Similarly if someone has different requirement anyone can modify compare function while declaring map.

由于 std::map 是关联数组,因此可以很容易地找到最大或最小的键。默认比较函数是 less(<) 运算符,因此最大的键将是映射中的最后一个元素。同样,如果有人有不同的要求,任何人都可以在声明映射时修改比较函数。

std::map< key, Value, compare< key,Value > >

std::map<键、值、比较<键、值>>

By default compare=std::less

默认情况下 compare=std::less