set
构造和赋值
set大小和交换
set插入和删除
set查找和统计
set和multiset的区别
pair对组的创建
利用仿函数来改变sort的规则
上代码:
#include <iostream>
#include <set>
#include <algorithm>
#include<string>
using namespace std;
class com
{
public:
bool operator()(int a, int b)
{
return a > b;
}
};
int main()
{
set< int >s;
s.insert(10);
s.insert(20);
s.insert(30);
s.insert(40);
//这里改变排序规则是改变排序的插入规则
set<int, com>s2;
s2.insert(20);
s2.insert(10);
}
//自定义类型的插入,并且改变顺序
#include <iostream>
#include <set>
#include <algorithm>
#include<string>
using namespace std;
class person
{
public:
person(string s1, int year, int len)
{
this->name = s1;
this->len = len;
this->year = year;
}
string name;
int year;
int len;
};
//按照身高降序,身高相同按照年龄降序
class com
{
public:
bool operator()(person p1, person p2)const
{
if (p1.year != p2.year)
return p1.year > p2.year;
else
{
return p1.len > p2.len;
}
}
};
int main()
{
person p1("刘备", 35, 175);
person p2("曹操", 45, 180);
person p3("孙权", 40, 180);
person p4("赵云", 35, 180);
//这里改变排序规则是改变排序的插入规则
set<person, com>s2;
s2.insert(p1);
s2.insert(p2);
s2.insert(p3);
s2.insert(p4);
for (set<person>::iterator it = s2.begin(); it != s2.end(); it++)
{
cout << "姓名 " << (*it).name << " 年龄是 " << it->year << " 身高是 " << it->len << endl;
}
}
注意const!