C ++如何找到std :: map中最大的关键字? [英] C++ How to find the biggest key in a std::map?
问题描述
目前我的解决方案是迭代地图来解决这个问题。
At the moment my solution is to iterate through the map to solve this.
我看到有一个 upper_bound
方法可以使这个循环更快,但是是否有更快或更简洁的方法?
I see there is a upper_bound
method which can make this loop faster, but is there a quicker or more succinct way?
推荐答案
结束: p>
The end:
m.rbegin();
地图(和集合)被排序,所以第一个元素是最小的,最后一个元素是最大的。默认地图使用 std :: less
,但是您可以切换比较器,这当然会改变最大元素的位置。 (例如,使用 std :: greater
将它放在 begin()
。
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()
.
请记住 rbegin
返回一个迭代器要获取实际的键,使用 m.rbegin() - >第一个
/ em>将其包装成一个功能,以清楚,虽然我不知道是否值得:
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屋!