Set and map in STL are ordered containers. If you want to set sorters based on your needs, there are usually two methods.
1. If the container directly stores the object, we can reload it in the object class. If the built-in type is not needed, there is a default
2. if not directly stored objects, such as object pointers (usually smart pointers), we need to define our own comparator. The comparator is generally written in two ways.
-> 1. Method for calling the operator by reloading the function in the class.
-> 2. Provides a comparator in the form of a function.
The first method is very simple and often used.
The following uses a simple example to describe how to write a comparator in the second method (for convenience, objects are temporarily stored ).
Student. h
Class student {public: Student (const string & SID): ID (SID) {} void print () const {cout <id <Endl;} string GETID () const {return ID;} PRIVATE: String ID ;};
Main. cpp
Struct compare {// override the operator () bool operator () (const student & LS, const student & RS) const {return ls. GETID () <Rs. GETID () ;}}; bool compare (const student & LS, const student & RS) {return ls. GETID () <Rs. GETID ();} int main () {/* The first type ----- define a class as the comparator */set <student, compare> MS; Ms. insert (student ("222"); Ms. insert (student ("111"); Ms. insert (student ("333"); Auto ite = Ms. B Egin (); For (; ite! = Ms. end (); ++ ITE) {ite-> Print ();}/* The second type ---- define a function as the comparator * // * set <student, bool (*) (const student & LS, const student & RS)> MS (compare); Ms. insert (student ("222"); Ms. insert (student ("111"); Ms. insert (student ("333"); Auto ite = Ms. begin (); For (; ite! = Ms. End (); ++ ITE) {ite-> Print ();} */return 0 ;}