C ++如何找到std :: map中最大的键? [英] C++ How to find the biggest key in a std::map?
问题描述
现在我的解决方案是迭代地图来解决这个问题。
我看到有一个 upper_bound $ c $
结束:
p> m.rbegin(); map>地图(和集合)进行排序,因此第一个元素是最小的,最后一个元素是最大的。默认地图使用 std :: less
,但是你可以切换比较器,这当然会改变最大元素的位置。 (例如,使用 std :: greater
将它放在 begin()
。
记住 rbegin 返回一个迭代器。要获取实际的键,使用 m.rbegin() - >第一
。虽然我不知道是否值得:
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 );
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 a quicker or more succinct way?
解决方案 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::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);
这篇关于C ++如何找到std :: map中最大的键?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!