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);
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…