Sort() sorting function usage in C++

sort(first_pointer,first_pointer+n,cmp)

This function can sort an array, or a linked list, or a vector.

Implementation principle: sort is not a simple quick sort, it optimizes the ordinary quick sort, in addition, it also combines insertion sort and push sort. The system will automatically select the appropriate sorting method according to your data form and data volume. This does not mean that it only selects one method for each sorting. It is to choose different methods in different situations in a complete sorting, such as giving a data volume. Larger arrays are sorted, start to use quick sort, segment recursion, after segmenting, when the amount of data in each segment reaches a small value, it will not continue to recurse, but choose insertion sort, if the recursion is too deep, he Push sort will be selected.

This function has 3 parameters:

Parameter 1: The first parameter is the first address of the array. Generally, the array name can be written, because the array name is a pointer constant.

Parameter 2: The second parameter is relatively easy to understand, that is, the first address plus the length n of the array (representing the next address of the tail address).

Parameter 3: You can leave it blank by default. If you leave it blank, sort will be sorted in ascending order by default. That is, 1,2,3,4 sort. You can also customize a sorting function and change the sorting method to descending order, that is, 4, 3, 2, 1.

To use this function you must first include:

#include <algorithm>

and export the namespace:

using namespace std;
Simple example: To sort the 0~n-1 elements of array A in ascending order, just write sort(A,A+n); the same is true for vector V, sort(v.begin(),v.end()) That's it.

Write your own collation function

For example :
bool compare(int a,int b)
{
  return a<b; //Ascending order, if it is changed to return a>b, it is descending order

}
Sort extension

sort is not only as simple as the above, we can extend sort, the key lies in the third parameter <cmp comparison function>, we want to sort in descending order, or I am not a simple array, but What about structures and classes? Here are some methods and examples.

Method 1: Define a comparison function (most commonly used)
//Case 1: array arrangement
int A[100];
bool cmp1(int a,int b)//int is an array data type
{
    return a>b;//sort in descending order
    //return a<b;//Default ascending order
}
sort(A,A+100,cmp1);

//Case 2: Structure sorting
Student Stu[100];
bool cmp2(Student a,Student b)
{
    return a.id>b.id;//Order in descending order by student number
    //return a.id<b.id;//In ascending order of student number
}
sort(Stu,Stu+100,cmp2);

Note: Comparison methods can also be defined in structures or classes.

Method 2: Use the standard library functions

In addition, we can be a little more lazy, and there are already existing ones in the standard library. Where is it? The answer is functional, let's include it and try it out. functional provides a bunch of template-based comparison function objects, they are: equal_to<Type>, not_equal_to<Type>, greater<Type>, greater_equal<Type>, less<Type>, less_equal<Type>. The usage of these things is known by the name. Here, we only need to use greater and less for sort. The usage is as follows:

● 升序:sort(begin,end,less<data-type>())

● 降序:sort(begin,end,greater<data-type>())

Disadvantages: It only implements simple sorting, and the structure is not applicable.

#include <iostream>
#include <cstdio>
#include <algorithm>
#include <functional>

using namespace std;
//easy to use
sort(A,A+100,greater<int>());//sort in descending order
sort(A,A+100,less<int>());//Ascending order

Method 3: Overload the comparison operator of a structure or class

//Case 1: Overloading inside the structure
typedef struct Student{
    int id;
    string name;
    double grade;

    bool operator<(const Student& s)
    {
        return id>s.id;//sort in descending order
        //return id<s.id;//Ascending order
    }
};
vector<Student> V;
sort(V.begin(),V.end());
//case 2: overloaded externally
vector<Student> V;
bool operator<(const Student& s1, const Student& s2)
{
    return s1.id>s2.id;//sort in descending order
    //return s1.id<s2.id;//Ascending order
}
sort(V.begin(),V.end());

Note: Be sure to overload the < operator, because the system defaults to descending order and uses the < operator.

Method 4: Declare a comparison class (less used)

struct Less
{
    bool operator()(const Student& s1, const Student& s2)
    {
        return s1.id<s2.id; //sort in ascending order
    }
};
sort(sutVector.begin(),stuVector.end(),Less());

A list (linked list) uses the sort() instance:

#include "stdafx.h"
#include <iostream>   
#include <list>   
#include <numeric>   
#include <algorithm>   
#include "stdlib.h"
#include <stdio.h>

using namespace std;

// Give list an alias LISTINT   
typedef list<int> LISTINT;   
//Create another alias LISTCHAR  
typedef list<int> LISTCHAR;

int _tmain(int argc, _TCHAR* argv[])
{

	//Use the list container to process integer data    
	//Create a list object named listOne with LISTINT   
	LISTINT listOne;   
	//declare i as an iterator   
	LISTINT::iterator i;

	//Add data to the listOne container from the front   
	listOne.push_front (2);   
	listOne.push_front (1);   

	//Add data to the listOne container from the end of the queue  

	listOne.push_back (5);   
	listOne.push_back (4);  
	listOne.push_back (9);
	listOne.push_back (7);
	listOne.push_back (12);

	//Display the data in listOne from front to back, the linked list before sorting   
	cout<<"listOne.begin()--- listOne.end():"<<endl;   
	for (i = listOne.begin(); i != listOne.end(); ++i)   
		cout << *i << " ";   
	cout << endl;  

	listOne.sort(); //sort with the sort() function, ascending by default


        //sorted list
	cout<<"listOne.begin()--- listOne.end():"<<endl;   
	for (i = listOne.begin(); i != listOne.end(); ++i)   
		cout << *i << " ";   
	cout << endl;


	system("pause"); //Exit after pressing any key



	return 0;
}

References: https://www.cnblogs.com/AlvinZH/p/6784862.html?utm_source=itdadao&utm_medium=referral

References: https://www.cnblogs.com/luorende/p/6121906.html




Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325932491&siteId=291194637