目录
前言
sort()函数是一个高效的排序函数,默认为升序,头文件<algorithm>。除了默认的排序方式,我们可以自己制定排序规则,为数组,容器甚至自己定义的结构体进行排序。
一、对数组、容器进行排序
-
对数组排序
#include <iostream>
#include <algorithm>
using namespace std;
int main()
{
int q[4]={1,5,4,3};
sort(q,q+4);
for(int i=0;i<4;i++)
{
cout<<q[i]<<" ";
}
cout<<endl;
return 0;
}
结果:1 3 4 5
-
对vector排序
#include <iostream>
#include <vector>
#include <algorithm>
#include <map>
using namespace std;
int main()
{
//vector 排序
vector<int> a={1,25,423,2,6}; //int 类型
vector<double>b ={1.2,3.4,45.67,4.2};//double 类型
vector<char> c={'a','c','r','b'}; //char 类型
sort(a.begin(),a.end());
sort(b.begin(),b.end());
sort(c.begin(),c.end());
for(auto i:a)
{
cout<<i<<" ";
}
cout<<endl;
for(auto i:b)
{
cout<<i<<" ";
}
cout<<endl;
for(auto i:c)
{
cout<<i<<" ";
}
cout<<endl;
return 0;
}
结果:
我们发现无论是数组还是容器,sort()最后一个参数指向的地址(q+4,a.end())是不取的,参与排序的值只取到结束地址的前一位。
-
对map进行排序
map在插入一对键值时,会按照key值的大小顺序存储,所以本身map的key值就是有序的。我们考虑对值进行排序,由于sort函数只能对顺序容器进行排序,无法直接操作关联容器,所以我们需要把map的键和值转存为一个pair类型的顺序容器如vector,随后对vector进行排序。
#include <iostream>
#include <vector>
#include <algorithm>
#include <map>
#include <string>
using namespace std;
bool cmp(pair<string,int>x,pair<string,int>y)
{
return x.second<y.second;
}
void sortMap(map<string,int>& sort_before, vector<pair<string,int>> &sort_after)
{
for(auto iter:sort_before)
{
sort_after.push_back(make_pair(iter.first,iter.second));
}
sort(sort_after.begin(),sort_after.end(),cmp);
}
int main()
{
map<string,int> student_score={{"lili",65},{"xiaoming",32},{"hanmeimei",98},{"lihua",45}};
vector<pair<string,int>>sort_score;
sortMap(student_score,sort_score);
for(auto student:sort_score)
{
cout<<student.first<<":"<< student.second<<endl;
}
return 1;
}
结果:
二、对自定义结构体属性排序
重点是定义好比较函数,具体以结构体的什么属性进行比较,也可以定义多个判断条件。
#include <iostream>
#include <vector>
#include <algorithm>
#include <map>
#include <string>
using namespace std;
struct student
{
string name;
int age=0;
};
bool cmp(student x,student y)
{
if(x.age==y.age) //按年龄排序,年龄相同按姓名首字母排序
{
return x.name<y.name;
}
else
{
return x.age<y.age;
}
}
int main()
{
vector<student> allStudent;
student lili,xiaoming,hanmeimei;
lili.name="lili";
lili.age=9;
xiaoming.name="xiaoming";
xiaoming.age=8;
hanmeimei.name="hanmeimei";
hanmeimei.age=9;
allStudent.push_back(lili);
allStudent.push_back(xiaoming);
allStudent.push_back(hanmeimei);
sort(allStudent.begin(),allStudent.end(),cmp);
for(auto student:allStudent)
{
cout<<student.name<<" : "<<student.age<<endl;
}
return 1;
}
结果: