如何在C++中声明一组pair的比较器
STL中的Set具有这样的属性,即仅在数据类型为整数时按排序顺序存储唯一值,在数据类型为字符串时按字典顺序从小到大存储。如果数据类型是pair,则set仅保留具有按照pair的第一个元素排序的不同对。
set of pairs的默认行为可以通过声明自定义比较器来修改或自定义。
语法:
set<pair<数据类型1,数据类型2,比较器>> set_name
比较器:
struct comparator {
// operator()重载
bool operator()(const pair<int,int> & p1,const pair<int,int> & p2){
// 自定义定义代码
}
};
示例1: 声明一组对的集合,其中包括将集合按照对的第2个元素排序的比较器。
// C++程序声明
// Set Of Pair的比较器
#include <bits/stdc++.h>
using namespace std;
// 声明一个自定义比较器
struct comp {
// Operator()重载
bool operator()(const pair<int, int>& p1,
const pair<int, int>& p2)
{
// 新的定义
return p1.second - p2.second;
}
};
int main()
{
// 用比较器声明一组pair的集合
set<pair<int, int>, comp> s;
// 将对添加到集合中
s.insert({ 4, 3 });
s.insert({ 5, 2 });
s.insert({ 6, 1 });
s.insert({ 7, 0 });
for (auto i = s.begin(); i != s.end(); i++) {
cout << i->first << " " << i->second << endl;
}
return 0;
}
输出
7 0
6 1
5 2
4 3
示例2: 声明一组对的集合,该集合基于对的第一个元素与第二个元素之间的差异进行排序的比较器。
// C++程序声明
// Set Of Pair的比较器
#include <bits/stdc++.h>
using namespace std;
// 声明一个自定义比较器
struct comp {
// Operator()重载
bool operator()(const pair<int, int>& p1,
const pair<int, int>& p2)
{
// 新的定义
int diff1 = p1.first - p1.second;
int diff2 = p2.first - p2.second;
return diff1 < diff2;
}
};
int main()
{
// 用比较器声明一组pair的集合
set<pair<int, int>, comp> s;
// 将对添加到集合中
s.insert({ 4, 3 });
s.insert({ 5, 2 });
s.insert({ 6, 4 });
s.insert({ 7, 3 });
for (auto i = s.begin(); i != s.end(); i++) {
cout << i->first << " " << i->second << endl;
}
return 0;
}
输出
4 3
6 4
5 2
7 3
示例3: 给定一组对,其中对的第一个元素是char,第二个元素是字符的级别。声明一个自定义比较器,使得在出现相同的第一个元素时,集合以等级的降序存储顺序。
// C++程序声明
// Set of Pair比较器
#include <bits/stdc++.h>
using namespace std;
// 声明自定义比较器
struct comp {
// Operator()重载
bool operator()(const pair<char, int>& p1,
const pair<char, int>& p2)
{
// 新定义
if (p1.first == p2.first) {
return p1.second > p2.second;
}
return p1.first < p2.first;
}
};
int main()
{
// 使用比较器声明一组配对
set<pair<char, int>, comp> s;
// 将配对添加到集合中
s.insert({ 'a', 3 });
s.insert({ 'c', 2 });
s.insert({ 'c', 4 });
s.insert({ 'c', 5 });
s.insert({ 'b', 4 });
s.insert({ 'b', 3 });
for (auto i = s.begin(); i != s.end(); i++) {
cout << i->first << " " << i->second << endl;
}
return 0;
}
输出
a 3
b 4
b 3
c 5
c 4
c 2