在构造map、set、multimap、multiset这些序列式容器时,默认按照key值来进行排序,比较器默认从小到大。在构造时加上greater<T> 会让容器的比较器按照key值从大到小排序,less<T>则相反。
#include<iostream>
#include<map>
#include<functional>
using namespace std;
int main() {
map<int, string,greater<int>> fruits;
fruits.insert(pair<int, string>(1, "apple"));
fruits.insert(pair<int, string>(2, "orange"));
fruits.insert(pair<int, string>(4, "banana"));
fruits.insert(pair<int, string>(3, "peach"));
for (auto i : fruits) {
cout << i.first << " " << i.second << endl;
}
return 0;
}

// STRUCT TEMPLATE greater
template <class _Ty = void>
struct greater {
typedef _Ty first_argument_type;
typedef _Ty second_argument_type;
typedef bool result_type;
constexpr bool operator()(const _Ty& _Left, const _Ty& _Right) const {
return _Left > _Right;
}
};
// STRUCT TEMPLATE less
template <class _Ty = void>
struct less {
typedef _Ty first_argument_type;
typedef _Ty second_argument_type;
typedef bool result_type;
constexpr bool operator()(const _Ty& _Left, const _Ty& _Right) const {
return _Left < _Right;
}
};```
本文介绍了STL中用于排序的greater<T>()和less<T>()函数。这两个函数分别用于设置容器如map、set等的比较器,greater<T>()使得元素按降序排列,而less<T>()则保持默认的升序排列。
972

被折叠的 条评论
为什么被折叠?



