摘要:C++ algorithm库中的sort函数可以通过数组的初始地址和结束地址对数组元素进行自定义排序。
1.函数导入在cpp文件中,头部写入#include以包含algorithm库
2.参数说明函数声明:
void sort (RandomAccessIterator first, RandomAccessIterator last, Compare comp);
- first:数组的起始地址。
- last:数组结束地址。(数组中最后一个元素的下一个地址)
- comp:自定义排序函数,默认升序。
自定义排序函数的声明形式:
bool comp(type x, type y);
返回值为true时,说明元素x与 元素y的排序满足自定义排序规则。
返回值为false时,说明元素x与 元素y的排序不满足自定义排序规则。
编译器:Microsoft Visual Studio 2019
语言:C++
源文件类型:cpp文件
- int数组排序
#include#include using namespace std; int main() { int nums[] = { 3,2,1,3 }; sort(nums, nums+4); // nums:数组起始地址(数组名指向数组的首元素) // nums + 4 :数组结束地址(起始地址偏移4个int类型位长) for (int num : nums) { cout << num << ' ' ; } cout << endl; }
输出结果:
1 2 3 3
- vector
数组排序
#include#include #include // 使用vector时,要包含其头文件 using namespace std; int main() { vector nums = { 3,2,1,3 }; sort(nums.begin(), nums.end()); // .begin():获取数组起始地址 // .end() :获取数组结束地址 for (int num : nums) { cout << num << ' ' ; } cout << endl; }
输出结果:
1 2 3 3
- vector
数组自定义排序
#include#include #include using namespace std; bool comp(int a, int b) { // 自定义降序 return a > b; } int main() { vector nums = { 3,2,1,3 }; sort(nums.begin(), nums.end(), comp); for (int num : nums) { cout << num << ' '; } cout << endl; }
输出结果:
3 3 2 1
2021.10.6 第一次编辑



