Cpp中修改sort函数排序方式,是通过自己写仿函数实现的,如下代码所示:
class MyCompare
{
public:
bool operator()(Person &p1, Person &p2)
{
if(p1.m_Age == p2.m_Age)
{
return p1.m_Height > p2.m_Height;
}
return p1.m_Age < p2.m_Age;
}
};
}
sort(MyCompare());
先对年龄进行升序排序,当年龄相同时,按照身高进行降序排序
那如何根据该思想修改Set容器内的默认排序呢?
Set容器在创建时就已经默认按升序排序了,所以要修改需要在声明处动手脚,具体就是通过
MyCompare
对()
的重载(仿函数):示例如下,按照降序排序
#include <iostream>
#include <set>
using namespace std;
//仿函数
class MyCompare
{
public:
bool operator()(int v1, int v2)
{
return v1 > v2;
}
};
void test01()
{
set<int,MyCompare> s1;
s1.insert(10);
s1.insert(40);
s1.insert(20);
s1.insert(60);
for(set<int,MyCompare>::iterator it = s1.begin(); it != s1.end(); it++)
{
cout << *it << " ";
}
cout << endl;
}
结果:
上面是对内置数据类型,当然对自定义数据类型更是如此:
#include <iostream>
#include <set>
using namespace std;
class Person
{
public:
Person(string name,int age)
{
this->m_Name = name;
this->m_Age = age;
}
int m_Age;
string m_Name;
};
//仿函数
class MyCompare
{
public:
bool operator()(const Person &p1, const Person &p2)
{
return p1.m_Age > p2.m_Age;
}
};
void test01()
{
set<Person,MyCompare> s1;
Person p1("刘备", 24);
Person p2("关羽", 28);
Person p3("张飞", 25);
Person p4("赵云", 21);
s1.insert(p1);
s1.insert(p2);
s1.insert(p3);
s1.insert(p4);
for(set<Person,MyCompare>::iterator it = s1.begin(); it != s1.end(); it++)
{
cout << (*it).m_Name << ":"<<(*it).m_Age<<endl;
}
}
map与set类似,通过仿函数实现(排序的依据为键值)