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.