C++ 标准库 <algorithm> 排序函数 sort

您所在的位置:网站首页 c中排序函数 C++ 标准库 <algorithm> 排序函数 sort

C++ 标准库 <algorithm> 排序函数 sort

2023-10-13 13:45| 来源: 网络整理| 查看: 265

摘要: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的排序不满足自定义排序规则。

3.应用实例 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 3,2,1,3 }; sort(nums.begin(), nums.end()); // .begin():获取数组起始地址 // .end() :获取数组结束地址 for (int num : nums) { cout vector nums = { 3,2,1,3 }; sort(nums.begin(), nums.end(), comp); for (int num : nums) { cout


【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3