Several basic uses of the sort function

1. First look at the most basic usage

#include<iostream>
#include<algorithm>//sort函数的头文件 
#include<vector>
using namespace std;
bool cmp(int a,int b)
{
    
    
	return a>b;
}
int main()
{
    
    
	int n;
	cin>>n;
	int a[n];
	//vector<int>a(n);
	for(int i=0;i<n;i++) cin>>a[i];
	sort(a,a+n);//sort函数默认排序是升序的 
	for(int i=0;i<n;i++) cout<<a[i]<<' ';
	cout<<endl;
	sort(a,a+n,cmp);
	for(int i=0;i<n;i++) cout<<a[i]<<' ';
	cout<<endl;
	
	return 0; 
}

Sample input:

10
1 0 9 7 6 5 3 2 4 8

Sample output:

0 1 2 3 4 5 6 7 8 9
9 8 7 6 5 4 3 2 1 0

Among them, sort(a,a+n) is the default sorting, which is ascending;
sort(a,a+n,cmp) adds a cmp function to change the sorting method to descending order
2. Used to arrange the parts in the array number

#include<iostream>
#include<algorithm>//sort函数的头文件 
#include<vector>
using namespace std;
bool cmp(int a,int b)
{
    
    
	return a>b;
}
int main()
{
    
    
	int n;
	cin>>n;
	//int a[n];
	vector<int>a(n);
	for(int i=0;i<n;i++) cin>>a[i];
	cout<<endl;
	sort(a.begin()+2,a.end()-2);
	for(int i=0;i<n;i++) cout<<a[i]<<' ';
	cout<<endl<<endl;
	sort(a.begin()+2,a.end()-2,cmp);
	for(int i=0;i<n;i++) cout<<a[i]<<' ';
	cout<<endl<<endl;
	return 0; 
}

Sample input:

10
0 2 1 4 3 8 6 7 5 9

Output:

0 2 1 3 4 6 7 8 5 9

0 2 8 7 6 4 3 1 5 9

Here sort(a.begin()+2,a.end()-2);, +2 and -2 indicate the first two, and the last two do not participate in the arrangement;

Note here the array int a[n];replaced vector<int>a(n);
used vector<int>a(n);to use when the header file #include<vector>
and the landlord here also do not understand, Cankuicankui!

The usage of cmp function here is the same as above.

Welcome to the advice of the big guys, if you don’t understand the cute ones, you can privately message q2651877067, I am very happy to answer QwQ for you! ! !

Guess you like

Origin blog.csdn.net/mmmjtt/article/details/114182805