STLset container sorting
learning target:
The default sorting rule of set container is from small to large, master how to change the sorting rule
Main technical points:
Using functors, you can change the sorting rules
Code example one:
#include<iostream>
#include<set>
using namespace std;
//set容器排序
class Mycompare
{
public:
bool operator()(int v1, int v2)
{
return v1 > v2;
}
};
void test01()
{
set<int>s1;
s1.insert(10);
s1.insert(40);
s1.insert(50);
s1.insert(30);
s1.insert(20);
for (set<int>::iterator it = s1.begin(); it != s1.end(); it++)
{
cout << *it << " ";
}
cout << endl;
//指定排序规则为从小到大
set<int, Mycompare>s2;
s2.insert(10);
s2.insert(40);
s2.insert(50);
s2.insert(30);
s2.insert(20);
for (set<int, Mycompare>::iterator it = s2.begin(); it != s2.end(); it++)
{
cout << *it << " ";
}
cout << endl;
}
int main()
{
test01();
system("pause");
return 0;
}
Summary: Use functors to specify the sorting rules of set containers
Code example two:
#include<iostream>
#include <string>
#include<set>
using namespace std;
//set容器排序,存放自定义数据类型
class Person
{
public:
Person(string name, int age)
{
this->m_Name = name;
this->m_age = age;
}
string m_Name;
int m_age;
};
class comPerson
{
public:
class comPerson
{
public:
bool operator()(const Person&p1, const Person&p2)
{
//按照年龄 降序
return p1.m_age > p2.m_age;
}
};
void test01()
{
//自定义数据类型,都会指定排序规则
set<Person, comPerson>s;
//创建对象
Person p1("刘备", 24);
Person p2("关羽", 34);
Person p3("张飞", 44);
Person p4("赵云", 54);
s.insert(p1);
s.insert(p2);
s.insert(p3);
s.insert(p4);
for (set<Person>::iterator it = s.begin(); it != s.end(); it++)
{
cout << "姓名:" << it->m_Name
<< " 年龄:" << it->m_age << endl;
}
}
int main()
{
test01();
system("pause");
return 0;
}
Summary:
For custom data types, set must specify the sorting rules to insert data