栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

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

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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

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

1.函数导入

在cpp文件中,头部写入#include以包含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.应用实例:

编译器:Microsoft Visual Studio 2019
语言:C++
源文件类型:cpp文件

  1. 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
  1. 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
  1. 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
------------------------------------------------------------End------------------------------------------------------------

2021.10.6 第一次编辑

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/297246.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号