Ordered containers customize sorters

Source: Internet
Author: User

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 ;}


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.