STL中的greater<T>()和less<T>()
阿新 • • 發佈:2020-12-16
技術標籤:C++
在構造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;
}
};```