Set container custom sorting in STL

Source: Internet
Author: User

Recently, I used STL to look at the data structure and learned a lot about the unfamiliar knowledge. We all know that the Sort Algorithm in STL is very useful and convenient. however, it seems that all of us have always used the int type to initialize these objects, so I will use a custom structure to initialize these objects, what should I do if I want to sort the size of a certain element in the Structure? I checked some information online and found a simple method based on my own learning and thinking. if you don't talk nonsense, read the code:

View plaincopy to clipboardprint?
# Include <iostream>
# Include <set>
Using namespace STD;
Struct Stu {
Char A [10];
Int S;

};
Class stu1: greater <Stu>
{
Public:
Bool operator () (STU B1, Stu B2) const {
Return b1.s <b2.s;
}
};
Main ()
{
Set <Stu, stu1>;
For (INT I = 0; I <3; I ++ ){
Stu D;
Cin> D. A> D. S;
A. insert (d );
}
Set <Stu, stu1 >:: iterator L;
For (L = A. Begin (); L! = A. End (); L ++ ){
Cout <L-> A <"" <L-> S <Endl;
}


}
# Include <iostream>
# Include <set>
Using namespace STD;
Struct Stu {
Char A [10];
Int S;

};
Class stu1: greater <Stu>
{
Public:
Bool operator () (STU B1, Stu B2) const {
Return b1.s <b2.s;
}
};
Main ()
{
Set <Stu, stu1>;
For (INT I = 0; I <3; I ++ ){
Stu D;
Cin> D. A> D. S;
A. insert (d );
}
Set <Stu, stu1 >:: iterator L;
For (L = A. Begin (); L! = A. End (); L ++ ){
Cout <L-> A <"" <L-> S <Endl;
}


}


The simple code is to inherit from greater (or less) in STL, and reload the () operator.

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.