Elaborate on the sort function in C + +

Source: Internet
Author: User

We have the most functions in the algorithm program on the line sort, but often forget how to write the comparison function, here in detail to do a summary.

1) prototype of the sort function in C + +

Default (1)
Template <class randomaccessiterator>  void sort (randomaccessiterator first, Randomaccessiterator last);
Custom (2)
Template <class Randomaccessiterator, class compare>  void Sort (randomaccessiterator first, Randomaccessiterator last, Compare comp);

Contains a randomaccessiterator iterator, a custom containing compare function class;

2) Compare function class

Compare function classes to compare elements and implement sorting, so there are three ways to implement the Compare class

1. The elements themselves contain comparative relationships, such as int,double, which can be directly compared

Greater<int> () decrements, less<int> () increments, can be implemented with pseudo functions, and also contains

2. The element itself is class or struct, and the inside of the class requires overloading the < operator to achieve the element comparison;

Caveats: bool operator< (const CLASSNAME & RHS) const; It is necessary to add a const if the parameter is a reference, so the temporary variable can be assigned, and the overloaded operator< is a constant member function, which can be called by the constant variable;

3. Out-of-class implementations, with BOOL (*) (Eletype a1,eletype A2) or bool (*) (const ELETYPE & A1, Const ELETYPE & A2)

4. Function class implementation, overloading () operator in class

struct Info {
int Val;
Info (int _val): Val (_val) {}
BOOL operator< (Info RHS) Const {
return val > rhs.val;
}
};
struct cmp{
BOOL Operator () (Info a1,info A2) const {
return a1.val > A2.val;
}
};
BOOL CMP (Info a1, info A2) {
return A1.val < A2.val;
}

Elaborate on the sort function in C + +

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.