Qsort/sort-C + + calls the CMP function to sort character array

Source: Internet
Author: User
Tags strcmp

This problem repeatedly met and forgot how to do once again, this time intends to thoroughly understand.

· C

The first order of the so-called character array should be the sort (char) *a[] array instead of (char) a[][], which cannot be directly called Qsort to implement its ordering.

CMP function notation:

1 int cmp (constvoidconstvoid *b) {2     return strcmp (* ((char* *) a), * ((char* *) b)); 3 }

It is easy to imagine that a string was assigned a specific storage space at initialization time, and we identified the string with its first address.

The ordering of the character array is actually the sort of the variable type: the character pointer (char*).

The result of the sort is actually a change in the position of the (character) pointer array element.

Therefore, the CMP function provides an interface to a const void pointer that represents the sorted object.

We're going to sort of *a, *b (type void), because what we're going to do is sort the strings (character pointers).

First, it is coerced into a pointer to a character pointer, which is equivalent to applying a pointer to the character p, and then A to P.

Then there is *a = P, which indirectly leads to a char type pointer to the corresponding string.

It is also possible to sort *a and *b with the strcmp function by comparing the original string.

The Qsort function:

1 sizeof (Char*), CMP);

· C++

C + + is easier to sort.

Sort function:

1 sort (A, a + N, CMP);

CMP functions:

1 BOOL CMP (charChar *b) {2     return0; 3 }

Because the interfaces provided by the CMP functions in C + + sort are directly oriented to the ordering of elements, we only need to consider the comparison of the character pointers themselves.

Qsort/sort-C + + calls the CMP function to sort character array

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.