sort函数的使用
Tip:
1、头文件 < algorithm >
2、默认从小到大排序
3、可定制比较函数,即定制自己的“小于”函数
#include <deque>
#include <iostream>
#include <vector>
#include <algorithm>
class student{
public:
student(std::string person_name, int person_score){
name = person_name;
score = person_score;
}
std::string name;
int score;
};
//自定义“小于”
bool compare(const int &a, const int &b){
return a > b;
}
bool comp(const student &a, const student &b){
return a.score > b.score;
}
int main()
{
using namespace std;
///array
int a[10] = { 9, 0, 1, 2, 3, 7, 4, 5, 100, 10 };
std::sort(a, a +10);
for (int i = 0; i < 10; i++)
cout << a[i] << " ";
std::cout << std::endl;
/*
* @deuqe or vector or map
*/
// std::deque <int> c1;
std::deque <int> c1;
c1.push_back(9);
c1.push_back(0);
c1.push_back(1);
c1.push_back(10);
c1.push_back(3);
c1.push_back(2);
c1.push_back(7);
c1.push_back(100);
c1.push_back(5);
c1.push_back(4);
std::deque <int> c2(c1);
cout << "The size of the deque is initially " << c1.size() << endl;
std::cout << "############### Init queue: " << std::endl;
for (std::deque<int>::iterator it = c1.begin(); it != c1.end(); it++){
std::cout << /*"c1[" << std::distance(c1.begin(),it) << "] :" << */*it << " ";
}
std::cout << std::endl;
std::cout << "############### Default Sort queue: Ascending" << std::endl;
sort(c1.begin(), c1.end());
for (std::deque<int>::iterator it = c1.begin(); it != c1.end(); it++){
std::cout << /*"c1[" << std::distance(c1.begin(),it) << "] :" << */*it << " ";
}
std::cout << std::endl;
std::cout << "############### Sort queue: Descending" << std::endl;
sort(c1.begin(), c1.end(),compare);
for (std::deque<int>::iterator it = c1.begin(); it != c1.end(); it++){
std::cout << /*"c1[" << std::distance(c1.begin(),it) << "] :" << */*it << " ";
}
std::cout << std::endl;
//类的排序
std::vector <student> students;
students.reserve(10);
for(int i =0; i <10; i++){
student one_student{"person"+std::to_string(i),c2.at(i)};
std::cout << one_student.name << ":"<< one_student.score << " " << std::endl;
students.push_back(one_student);
}
std::sort(students.begin(), students.end(), comp);
std::cout << "############### Sort students queue: Descending" << std::endl;
for(auto &it : students){
std::cout << it.name << ":" << it.score << std::endl;
}
}
备注:
关于sort数组时,数组总共有10个元素,a[0]~a[9], 但是缺是:sort(a, a+10); 那是因为sort方法实际上最后一位地址对应的数是不取的,如果换成a+9,则最后一个元素将不参与排序。