set容器默认是以升序方式对数据进行排序。若要改变它的排序方式,应在创建容器变量时使用仿函数。
一、简单地对数据进行降序排序
#include<iostream>
#include<set>
using namespace std;
//写仿函数,重载括号运算符,放在类中。
class temp
{
public:
//注意,是bool类型
bool operator()(const int num1, const int num2)
{
return num1 > num2;
}
};
int main()
{
//在声明容器时将有函数的类名从第二个接口传入
set<int, temp> s;
s.insert(200);
s.insert(500);
s.insert(300);
s.insert(700);
s.insert(100);
//打印容器
for (set<int, temp>::iterator it = s.begin(); it != s.end(); it++)
{
cout << *it << ' ';
}
cout << endl;
system("pause");
}
运行结果:
700 500 300 200 100
请按任意键继续. . .
二、对自定义类型进行降序排序
#include<iostream>
#include<set>
#include<string>
using namespace std;
class person
{
public:
person(string name, int height)
{
this->pheight = height;
this->pname = name;
}
string pname;
int pheight;
};
//写仿函数,重载括号运算符,放在类中。
class temp
{
public:
//注意,是bool类型, 且参数列表里要加const
bool operator()(const person &p1, const person &p2)
{
return p1.pheight > p2.pheight;
}
};
int main()
{
//在声明容器时将有函数的类名从第二个接口传入
person p1("Joe", 178);
person p2("Sue", 168);
person p3("Peter", 190);
person p4("Frank", 185);
set<person, temp> s;
s.insert(p1);
s.insert(p2);
s.insert(p3);
s.insert(p4);
//打印容器中内容
for (set<person, temp>::iterator it = s.begin(); it != s.end(); it++)
{
cout << (*it).pname << ' ' << (*it).pheight << endl;
}
system("pause");
}
运行结果:
Peter 190
Frank 185
Joe 178
Sue 168
请按任意键继续. . .