1.sort算法排序
sort(起始地址,结束地址)基本的数据类型从小到大排序
以int数据类型为例:
vector<int> v = {2,1,4,5,3};
sort(v.begin(), v.end());
输出结果为
PS C:\Users\17635> cd "c:\Users\17635\Desktop\kbfvictory\c++练习\" ; if ($?) { g++ kbf.cpp -o kbf } ; if ($?) { .\kbf }
1
2
3
4
5
也可以使用sort(v.begin(), v.end(), less<int>())这种方式实现。
从大到小可以使用sort(ve.begin(), v.end(), greater<int>())这种方式实现。
自定义数据类型排序,可以写个bool函数实现,如下:
struct Person{
Person(int age, string name):m_age(age),m_name(name){};
string m_name;
int m_age;
};
bool cmp(Person a, Person b){
return a.m_age > b.m_age;
}
int main(){
Person p1(2, "a"), p2(1, "b"), p3(3, "c");
vector<Person> v = {p1,p2,p3};
for(auto ch : v){
cout << ch.m_age << endl;
}
sort(v.begin(), v.end(), cmp);
for(auto ch : v){
cout << ch.m_age << endl;
}
return 0;
}
输出结果如下:
尝试新的跨平台 PowerShell https://aka.ms/pscore6
PS C:\Users\17635> cd "c:\Users\17635\Desktop\kbfvictory\c++练习\" ; if ($?) { g++ kbf.cpp -o kbf } ; if ($?) { .\kbf }
2
1
3
3
2
1
PS C:\Users\17635\Desktop\kbfvictory\c++练习>
bool函数里面当第一个参数大于第二个参数为从大到小排序;反之,当第一个参数小于第二个参数时为从小到大排序。
2.priority_queue排序
当我们需要用有限队列priority_queue对自定义数据类型进行排序时需要传入三个数据类型来构建对象 priority_queue<排序对象的数据类型, vector<排序对象的数据类型>, 重载()的自定义数据类型(里面包含重载())>, 如下:
#include<iostream>
#include<vector>
#include<algorithm>
#include<string>
#include<queue>
using namespace std;
struct Person{
Person(int age, string name):m_age(age),m_name(name){};
string m_name;
int m_age;
};
struct cmp
{
bool operator()(Person a, Person b){
return a.m_age < b.m_age;
}
};
int main(){
// Person p1(2, "a"), p2(1, "b"), p3(3, "c");
// priority_queue<Person, vector<Person>, cmp> q;
// q.push(p1);
// q.push(p2);
// q.push(p3);
// for(int i = 0; i < 3; i++){
// cout << q.top().m_age << endl;
// q.pop();
// }
priority_queue<int, vector<int>> q;
q.push(2);
q.push(1);
q.push(3);
int a = q.size();
cout << a << endl;
for(int i = 0; i< a; i++){
cout << q.top() << endl;
q.pop();
}
return 0;
}
结果如下:
尝试新的跨平台 PowerShell https://aka.ms/pscore6
PS C:\Users\17635> cd "c:\Users\17635\Desktop\kbfvictory\c++练习\" ; if ($?) { g++ kbf.cpp -o kbf } ; if ($?) { .\kbf }
3
3
2
1
PS C:\Users\17635\Desktop\kbfvictory\c++练习>
当排序的数据类型为基本数据类型时,第三个数据类型可不写,默认从小到大排序(注意:由于时对列,头只能进入数据而为尾部是出数据,所有如果以出对的顺序来访问元素的话,会从大到小显示,刚好与我们排序相反,因为我们是从队尾开始访问数据)