C + + sort function sort (), meaning and usage of qsort (), reverse order of string strings, etc.

Source: Internet
Author: User

When we went to school we learned a lot of sorting algorithms, but we also encapsulated the sort function in C++stl, the header file is # include <algorithm>

Name of function

Function description

Sort

Sort all elements of a given interval

Stable_sort

Stable ordering of all elements in a given interval

Partial_sort

Sort all elements of a given interval

Partial_sort_copy

Copy and sort the given interval

Nth_element

Find the element corresponding to a position in a given interval

is_sorted

Determine if an interval has been sequenced.

Partition

Put elements that meet a certain condition in front

Stable_partition

Relatively stable so that elements that meet a certain condition are placed in front

Sort (begin,end), which represents a range, for example:

#include "stdafx.h" #include <algorithm> #include "iostream" using namespace std; int main (int argc, char* argv[]) {     int a[11]={2,4,5,6,1,2,334,67,8,9,0},i;     for (i=0;i<11;i++)         cout<<a[i]<< ', ';     Sort (a,a+11);     cout<< ' \ n ';     for (i=0;i<11;i++)         cout<<a[i]<< ', ';     return 0; }

  

The output would be to sort the array a in ascending order, and perhaps someone would ask how to use it in descending order? This is what the next discussion is about.

One is to write a comparison function to implement, and then call the third parameter Sort:sort (begin,end,compare).

For the list container, this method also applies, compare as a sort parameter, namely: Sort (Compare).

1) Write your own compare function:

#include "stdafx.h" #include <algorithm> #include "iostream" using namespace std; BOOL Compare (int a,int b) {     return a>b;   In descending order, if you change to return a<b, the ascending}int main (int argc, char* argv[]) {     int a[11]={2,4,5,6,1,2,334,67,8,9,0},i;     for (i=0;i<11;i++)         cout<<a[i]<< ', ';     Sort (a,a+11,compare);     cout<< ' \ n ';     for (i=0;i<11;i++)         cout<<a[i]<< ', ';     

  

2) Further, make this operation more adaptable to change. That is, you can give a comparison function a parameter that indicates whether to sort in ascending or descending order, which turns to the function object's appearance.
For the sake of description, I first define an enumeration type Enumcomp to represent ascending and descending. Very simple:
Enum ENUMCOMP{ASC,DESC};
It then starts with a class to describe the function object. It will decide whether to use "<" or ">" depending on its parameters.

Class Compare
{
Private
Enumcomp comp;
Public
Compare (Enumcomp C): Comp (c) {};
BOOL operator () (int num1,int num2)
{
Switch (COMP)
{
Case ASC:
Return num1<num2;
Case DESC:
Return num1>num2;
}
}
};

Next use Sort (Begin,end,compare (ASC) to implement ascending, sort (Begin,end,compare (DESC) implementation in descending order.

The complete code is

#include "stdafx.h" #include <algorithm> #include "iostream" using namespace std; Enum Enumcomp{asc,desc};class Compare {private:     Enumcomp comp; public:     Compare (Enumcomp C): Comp (c) {};     BOOL operator () (int num1,int num2)     {         switch (comp)         {case         ASC:             return num1<num2;         Case DESC:             return num1>num2;         }}     ; int main (int argc, char* argv[]) {     int a[11]={2,4,5,6,1,2,334,67,8,9,0},i;     for (i=0;i<11;i++)         cout<<a[i]<< ', ';     Sort (A,a+11,compare (ASC));     cout<< ' \ n ';     for (i=0;i<11;i++)         cout<<a[i]<< ', ';     

  

3) In fact, for such a simple task (type support "<", ">" and other comparison operators), it is completely unnecessary to write a class. The standard library already has a ready-made, in the functional, include in the line. Functional provides a bunch of template-based comparison function objects. They are (see name to know meaning):equal_to<type>, not_equal_to<type>, greater<type>, greater_equal<type>, Less<type>, less_equal<type>. For this problem, greater and less are enough to come straight to use:

• Ascending: Sort (begin,end,less<data-type> ());
• Descending: Sort (begin,end,greater<data-type> ()).

#include "stdafx.h" #include <algorithm> #include "iostream" #include "functional" using namespace std; int main (int argc, char* argv[]) {     int a[11]={2,4,5,6,1,2,334,67,8,9,0},i;     for (i=0;i<11;i++)         cout<<a[i]<< ', ';     Sort (a,a+11,greater<int> ());     cout<< ' \ n ';     for (i=0;i<11;i++)         cout<<a[i]<< ', ';     

  


4) Since there is an iterator, if it is a string you can use a reverse iterator to complete the order, the program is as follows:

#include "stdafx.h" #include <algorithm> #include "iostream" #include "string" using namespace std; int main (int argc, char* argv[]) {    string str= "Avfgrtty";    int i;     cout<<str<< ' \ n ';     For (String::reverse_iterator Rit=str.rbegin (); Rit!=str.rend (); ++rit)     cout << *rit;     cout<<endl;     return 0; }

  

Qsort (): Fast sorting algorithm
Prototype:
_crtimp void __cdecl qsort (void*, size_t, Size_t,int (*) (const void*, const void*));

Explanation: Qsort (array name, number of elements, space occupied by elements (sizeof), comparison function)
The comparison function is a self-written function that follows the format of the int COM (const void *a,const void *b).
When a-B relationship is > < =, a positive negative value of 0 (or vice versa) is returned respectively.
When you use a B to cast the type, the operation is performed after the type of the response is converted from void *.
Array subscript starts from zero, number is N, subscript 0-(n-1).

#include "stdafx.h" #include <algorithm> #include "iostream" #include "string" using namespace Std;int compare (cons t void *a,const void *b) {     return * (int*) b-* (int*) A;   } int main (int argc, char* argv[]) {     int a[11]={2,4,5,6,1,2,334,67,8,9,0},i;     for (i=0;i<11;i++)         cout<<a[i]<< ', ';     Qsort (void *) a,11,sizeof (int), compare);     cout<< ' \ n ';     for (i=0;i<11;i++)         cout<<a[i]<< ', ';     return 0;}

  

Related:
1) Why do you have to give the number of elements?
Because the array doesn't know how many of its own elements
2) Why do you have to give size?
Because Qsort doesn't know the units it wants to sort.
3) Why do you have to write the ugly function that compares the two values?
Because qsort requires an indicator to point to a function because it does not know what type of element it is ordering.
4) Why does the comparison function used by Qsort accept a const void* argument instead of a char* argument?
Because qsort can sort the values of non-strings.

The above example is based on the vc6.0

C + + sort function sort (), meaning and usage of qsort (), reverse order of string strings, etc.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.