C++map(unordered_map) 的小于号

7/9/2019

之前打题的时候想从一个map中取出值最大的元素 然后顺手就写了

    auto mx = max_element(mp.begin(), mp.end());
1

然后怎么调都调不出来样例=_=

后来冷静分析了一下 map<T1,T2>map<T1, T2>中的每个元素都是pair<T1,T2>pair<T1, T2>, 所以max_elementmax\_element调用的应该是pair<T1,T2>pair<T1, T2>的小于号 即先比较firstfirst, 再比较secondsecond 看了下源码果然如此 (在stl_pair.h中)

template<class _T1, class _T2>
    inline _GLIBCXX_CONSTEXPR bool
    operator<(const pair<_T1, _T2>& __x, const pair<_T1, _T2>& __y)
    { 
    	return __x.first < __y.first
	     || (!(__y.first < __x.first) && __x.second < __y.second); 
	}
1
2
3
4
5
6
7

所以想取出值最大的元素,需要给max_elementmax\_element传入一个cmp函数cmp函数

    auto mx = max_element(mp.begin(), mp.end(), [](const pair<int, int> &x, const pair<int, int> &y){
        return x.second < y.second;
    });
1
2
3

传入的cmpcmp定义的是operator<operator<,注意别写反

Last Updated: 4/3/2022, 12:55:14 AM