一、头文件

#include<algorithm>
using namespace std;

二、使用sort()

1.函数原型

sort(begin, end)
sort(begin, end, pred)

作用:可以用来排序数组容器等。

参数:

  • begin:排序区间的起始位置
  • end:排序区间的结束位置(不包括)
  • pred:自定义排序方式

排序区间:[ begin, end )

2.简单地使用sort()

用于基本类型的排序,如int。

(1)默认排序

sort函数没有第三个参数,实现的是从小到大(升序)排列

排序数组

#include<iostream>
#include<algorithm>
using namespace std;
int main()
{
	int a[10] = { 9,6,3,8,5,2,7,4,1,0 };

	sort(a, a + 10);		//从下标begin不到下标end,要排序十个元素就加10
	
	for (int i = 0; i < 10; i++)
		cout << a[i] << ' ';
	cout << endl;
	//0 1 2 3 4 5 6 7 8 9
	return 0;
}

排序容器

#include<iostream>
#include<algorithm>
#include<vector>
using namespace std;
int main()
{
	vector<int> v{ 9, 6, 3, 8, 5, 2, 7, 4, 1, 0 };
	
	sort(v.begin(), v.end());

	for (int i = 0; i < v.size(); i++)
		cout << v[i] << ' ';
	cout << endl;
	//0 1 2 3 4 5 6 7 8 9
	return 0;
}

(2)两种常用的排序方法

  • 升序:sort(begin, end, less<data-type>());
  • 降序:sort(begin, end, greater<data-type>())
sort(a, a + 10, less<int>());		//升序
sort(a, a + 10, greater<int>());	//降序

排序数组

#include<iostream>
#include<algorithm>
using namespace std;
int main()
{
	int a[10] = { 9,6,3,8,5,2,7,4,1,0 };

	sort(a, a + 10,greater<int>());

	for (int i = 0; i < 10; i++)
		cout << a[i] << ' ';
	cout << endl;
	//9 8 7 6 5 4 3 2 1 0
	return 0;
}

排序容器

#include<iostream>
#include<algorithm>
#include<vector>
using namespace std;
int main()
{
	vector<int> v{ 9, 6, 3, 8, 5, 2, 7, 4, 1, 0 };
	
	sort(v.begin(), v.end(),greater<int>());

	for (int i = 0; i < v.size(); i++)
		cout << v[i] << ' ';
	cout << endl;
	//9 8 7 6 5 4 3 2 1 0
	return 0;
}

3.自定义使用sort()

只用重写排序方式。这种方法出乎意料地简单有效,而且复杂类型的操作也有效。

自定义排序方式:

//重写排序方法
bool comp(const double &a, const double &b){
//常引用const T &xxx
    return a< b;
    //<代表升序,>代表降序
}
#include<iostream>
#include<algorithm>
#include<vector>
using namespace std;

//重写排序方法
bool comp(const double &a, const double &b){
//常引用const T &xxx
    return a< b;
    //<代表升序,>代表降序
}

int main()
{
    vector<double> c{5,4,1,3,2};

	//调用sort()函数
    sort(c.begin(),c.end(),comp);

    for(int i=0;i<5;i++)
    {
        cout<<c.at(i)<<' ';
    }
    //1 2 3 4 5
	return 0;
}
#include <iostream>
#include <algorithm>
using namespace std;
typedef pair<int, int> node;

//重写排序方法
bool comp(const node &a, const node &b)
{
	//常引用const T &xxx
	return a.first < b.first || a.first == b.first && a.second <= b.second;
	//<代表升序,>代表降序
}

int main()
{
	node a[] = {{1, 2}, {2, 3}, {2, 1}};
	int length = sizeof(a) / sizeof(node);
	
	sort(a, a + length, comp);
	
	for (int i = 0; i < length; i++)
	{
		cout << a[i].first << " " << a[i].second << endl;
	}
	return 0;
}
/**
1 2
2 1
2 3
*/
Logo

旨在为数千万中国开发者提供一个无缝且高效的云端环境,以支持学习、使用和贡献开源项目。

更多推荐