# 使用std::pair作为std::set的key

1. 使用默认排序

#include <iostream>
#include <set>
#include <utility>

int main()
{
std::set<std::pair<std::string, int>> set = {
{"A", 4}, {"B", 4}, {"C", 1}, {"A", 0}, {"B", 3}
};

for (auto const &p: set) {
std::cout << p.first << " " << p.second << '\n';
}

return 0;
}

Output:

{A:0}

{A:4}

{B:3}

{B:4}

{C:1}

template <class T1, class T2>
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);
}

2. 使用比较对象

#include <iostream>
#include <set>
#include <utility>

struct comp
{
template<typename T>
bool operator()(const T& l, const T& r) const
{
if (l.first == r.first)
return l.second > r.second;

return l.first < r.first;
}
};

int main()
{
std::set<std::pair<std::string,int>, comp> set = {
{"A", 4}, {"B", 4}, {"C", 1}, {"A", 0}, {"B", 3}
};

for (auto const &p: set) {
std::cout << "{" << p.first << ":" << p.second << "}\n";
}

return 0;
}

Output:

{A:4}

{A:0}

{B:4}

{B:3}

{C:1}

3. 特例化std::less

#include <iostream>
#include <set>
#include <utility>

namespace std {
template<typename T1, typename T2>
struct less<std::pair<T1, T2>>
{
bool operator()(const std::pair<T1, T2>& l,
const std::pair<T1, T2>& r) const
{
if (l.first == r.first)
return l.second > r.second;

return l.first < r.first;
}
};
}

int main()
{
std::set<std::pair<std::string, int>> set = {
{"A", 4}, {"B", 4}, {"C", 1}, {"A", 0}, {"B", 3}
};

for (auto const &p: set) {
std::cout << "{" << p.first << ":" << p.second << "}\n";
}

return 0;
}

Output:

{A:4}

{A:0}

{B:4}

{B:3}

{C:1}

https://www.techiedelight.com/use-std_pair-as-key-std_set-cpp/

©️2019 CSDN 皮肤主题: 大白 设计师: CSDN官方博客