C++sort function Usage __jquery

Source: Internet
Author: User

Definition in MSDN: Template<class ranit>
void Sort(Ranit-I, ranit last); --> 1)
Template<class Ranit, Class pred>
void Sort(Ranit, Ranit last, Pred PR); --> 2)

Header file:
#include <algorithm>
using namespace Std;

1. The default sort function is in ascending order. Corresponds to 1)
Sort (a,a+n); Two parameters are the first and end addresses of the array to be sorted, respectively
2. You can write a CMP function by yourself, sorted by specific intent. Corresponds to 2)
For example:
int cmp (const int &A, const int &b) {
if (a > B)
return 1;
return 0;
Sort (a,a+n,cmp);
Is array a descending sort
Another example:
int CMP (const point &a, const point &b) {
if (a.x < b.x)
return 1;
if (a.x = = b.x) {
if (A.y < B.Y)
return 1;
return 0;
return 0;
Sort (a,a+n,cmp);
is sorted by x in ascending order, or Y ascending if x is equal

Similar to the qsort in C, the following is attached to the Qsort method of use:

#include <stdlib.h>

Format qsort (array_name,data_number,sizeof (data_type), Compare_function_name) (void*) bsearch (Pointer_to_key_word, Array_name,find_number,

sizeof (data_type), compare_function_name)


int Cmp (const void*a,const void *b)


Int*pa= (int*) a,*pb= (int*) b;

if (*PA>*PB) return 1;

else if (*PA==*PB) return 0;

else return-1;


Qsort (data,n,sizeof (int), CMP); Quick sort on int arrays (not in descending order)

p= (int*) bsearch (&a,data,n,sizeof (int), CMP);

Related Article

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.