C++ STL 标准库中的 sort() 函数,本质就是一个模板函数,位于头文件。
该函数专门用来对容器或普通数组中指定范围内的元素进行排序,默认升序排序,除此之外我们也可以选择标准库的其它排序规则,或者自定义排序规则。
- 函数参数模版
void sort (RandomAccessIterator first, RandomAccessIterator last, Compare comp); // 按照指定的 comp 排序规则,对 [first, last) 区域内的元素进行排序 // firt: 起始位置,左闭; // last: 结束为止,右开; // comp: 排序规则(比较器),可以省略,默认升序。
- 对数组升序排序:
#include#include using namespace std; main() { //sort函数第三个参数采用默认从小到大 int a[]={45,12,34,77,90,11,2,4,5,55}; sort(a, a + 10); for(int i=0;i<10;i++) cout<
- 自定义排序规则:
#include#include using namespace std; bool ascend(int a, int b){ return a < b; // true时 a 在 b 前面,即升序 } bool descend(int a, int b){ return a > b; // true时 a 在 b 前面,即降序 } int main(){ int nums[] = {1,3,2,6,5,4,8,7}; sort(nums, nums + 8, ascend); // 升序 for(int i : nums) cout << i << " "; cout << endl; sort(nums, nums + 8, descend); // 降序 for(int i : nums) cout << i << " "; return 0; } 对于int, double等基本数据类型,标准库已有现成的排序规则,如
equal_to()、not_equal_to ()、greater ()、greater_equal ()、less ()、less_equal ()等可以直接调用。
升序:sort(begin, end, less());
降序:sort(begin, end, greater.());
- 对vector进行排序
#include#include #include using namespace std; int main(){ vector vec = {1,2,6,8,4,1,0,3,-1}; sort(vec.begin(), vec.end(), greater ()); // 升序 for(int i : vec) cout << i << " "; cout << endl; sort(vec.begin(), vec.end(), less ()); // 降序 for(int i : vec) cout << i << " "; return 0; }
- 结构体二级排序(自定义排序规则)
#include#include #include using namespace std; struct student { string name; int math; int eng; }; bool comp(student a, student b){ // 先按数学成绩降序,再看英语成绩降序 if(a.math == b.math) return a.eng > b.eng; return a.math > b.math; } int main(){ student students[] = { {"aa", 80, 90}, // cc 100 60 {"bb", 90, 80}, // dd 90 100 {"cc", 100 ,60}, // bb 90 80 {"dd", 90, 100} // aa 80 90 }; sort(students, students + 4, comp); for(auto stu : students){ cout << stu.name << " " << stu.math << " " << stu.eng << endl; } return 0; }
- 结构体或类二级排序(内部重载<运算符)
#include#include #include using namespace std; struct student { string name; int math; int eng; // 重载 < 运算符, 默认a < b成立时a在b前面 inline bool operator < (const student & anoter) const { if(math == anoter.math) return eng > anoter.eng; return math > anoter.math; } }; int main(){ student students[] = { {"aa", 80, 90}, // cc 100 60 {"bb", 90, 80}, // dd 90 100 {"cc", 100 ,60}, // bb 90 80 {"dd", 90, 100} // aa 80 90 }; sort(students, students + 4); // 默认a < b成立时a在b前面,则重载 < 运算符 for(auto stu : students){ cout << stu.name << " " << stu.math << " " << stu.eng << endl; } return 0; }



