C++ sort function explanation

Before we start, let's look at a topic

topic description

Given a number of integers, and output (sorted, from large to small)

input sample

5 8 9 6 4 2 3 7 1 10

output sample

10 9 8 7 6 5 4 3 2 1

Code

First, explain sortthe application of the sorting function

sort(开始位置,结束位置,参数)

C++By default, the language puts the small numbers first. If you want to put the big numbers first, you must add parameters:

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

This is sorted from largest to smallest

Of course, if the parameters are written like this:

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

The program will be sorted from small to large


Ok, now I believe that everyone has a certain idea about this topic, let's write code

#include <bits/stdc++.h>
using namespace std;

int main ()
{
    
    
	int a[10]; //定义变量
	for(int i=0;i<10;i++){
    
    
		cin>>a[i]; //循环输入
	}
	sort(a,a+10,greater<int>()); //sort排序,开始位置默认+0
	//比如:sort(a+0,a+10,greater<int>()); 也是对的
	for(int i=0;i<10;i++){
    
    
		cout<<a[i]<<' '; //输出
	}
    return 0;
}

operation result:

test 1
So is there an easier way?
of course

We can write a function of Boolean type, the return value is True, put ainb front; the return value is False, bput ina front

bool cmp(int a,int b){
    
    
	return a>b;
}

Then, just fill in the parameters sortin the functioncmp

sort(a,a+10,cmp);

Full code:

#include <bits/stdc++.h>
using namespace std;
bool cmp(int a,int b){
    
    
	return a>b;
}
int main ()
{
    
    
	int a[10]; //定义变量
	for(int i=0;i<10;i++){
    
    
		cin>>a[i]; //循环输入
	}
	sort(a,a+10,cmp); //sort排序
	for(int i=0;i<10;i++){
    
    
		cout<<a[i]<<' '; //输出
	}
    return 0;
}

test2

Summarize

sortFunction usage:
sort(开始位置,结束位置,参数)

Among them, the parameters can be less<int>(), greater<int>(), or other custom functions

CLanguage default sort order:从小到大

For sorting from small to large less<int>(), use from large to smallgreater<int>()

bool cmp(int a,int b){
    
    
	return a>b; //从大到小
	return a<b; //从小到大,也可以写成 return b>a;
}

Guess you like

Origin blog.csdn.net/weixin_45122104/article/details/125996916
Recommended