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 + +