STL 模板库-set
前言
使用set需要加上头文件#include<set>
使用multiset需要加上头文件#include<multiset>
一、set是什么?
set 插入数据时自动排序(不能插入重复数字)multiset 插入数据时自动排序(能插入重复数字)
二、使用步骤
1.改变排序规则
#include<iostream>
#include<set>
using namespace std;
class mper {
public:
bool operator()(int a,int b) {//仿函数
return a > b;
}
};
void text() {
set<int, mper>s;
s.insert(90);
s.insert(1000);
s.insert(40);
s.insert(990);
for (set<int, mper>::iterator it = s.begin(); it != s.end(); it++)
cout << *it << " ";
}
int main() {
text();
}
set装入自定义数据类型 要提前指定排序规则
#include<iostream>
#include<set>
#include<string>
using namespace std;
class person {
public:
string name;
int age;
person(string name, int age) {
this->name = name;
this->age = age;
}
};
class com {
public:
bool operator()(person a, person b) {
return a.age > b.age;
}
};
int main() {
person p("小明", 20);
person p1("小l", 29);
person p2("小f", 22);
person p3("小h", 21);
set<person,com >s;
s.insert(p);
s.insert(p1);
s.insert(p2);
s.insert(p3);
for (set<person,com>::iterator it = s.begin(); it != s.end(); it++)
cout << it->name << endl;
}
2.对组
#include<iostream>
using namespace std;
int main() {
pair<int, char>p(20, 'k');
cout << p.second << " " << p.first<<endl;
}```
# 总结
球球了,好累啊