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

摘要:C++ algorithm库中的sort函数可以通过数组的初始地址和结束地址对数组元素进行自定义排序。

1.函数导入

在cpp文件中,头部写入#include<algorithm>以包含algorithm

2.参数说明

函数声明:

void sort (RandomAccessIterator first, RandomAccessIterator last, Compare comp);

  1. first:数组的起始地址。
  2. last:数组结束地址。(数组中最后一个元素的下一个地址)
  3. comp:自定义排序函数,默认升序。

自定义排序函数的声明形式:

bool comp(type x, type y);

返回值为true时,说明元素x与 元素y的排序满足自定义排序规则。
返回值为false时,说明元素x与 元素y的排序不满足自定义排序规则。

3.应用实例

  1. int数组排序
#include<iostream>
#include<algorithm>
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
  1. vector<int>数组排序
#include<iostream>
#include<algorithm>
#include<vector>  // 使用vector时,要包含其头文件
using namespace std;

int main() {
	vector<int> nums = { 3,2,1,3 };

	sort(nums.begin(), nums.end());
	// .begin():获取数组起始地址
	// .end() :获取数组结束地址
	
	for (int num : nums) {
		cout << num << ' ' ;
	}
	cout << endl;

}

输出结果:

1 2 3 3
  1. vector<int>数组自定义排序
#include<iostream>
#include<algorithm>
#include<vector>
using namespace std;

bool comp(int a, int b) {  // 自定义降序
	return a > b;
}

int main() {
	vector<int> nums = { 3,2,1,3 };

	sort(nums.begin(), nums.end(), comp);

	for (int num : nums) {
		cout << num << ' ';
	}
	cout << endl;

}

输出结果:

3 3 2 1

END

2021.10.8 第一次编辑

  • 6
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值