Struct must be overloaded in STL.

Source: Internet
Author: User

In STL applications, we often use struct, which requires us to reload operators with specific requirements. For example, in STL, sorting is performed by default using a smaller number. Therefore, when sorting the struct, We need to reload the minor signs.

Example:

# Include <map>
# Include <iostream>
# Include <string>

Using namespace std;

// Student Information
Typedef struct tagStudentInfo
{
Int nID;
String strName;
Bool operator <(const tagStudentInfo & A) const
{
If (nID <A. nID) return true; // compare nID first
If (nID = A. nID) return strName. compare (A. strName) <0; // compare strName
Return false;
}

} StudentInfo, * pstudentInfo;

Int main ()
{
// Map scores with student information
Map <StudentInfo, int> mapStudent;

StudentInfo studentInfo;

StudentInfo. nID = 1;
StudentInfo. strName = "student_one ";
MapStudent. insert (map <StudentInfo, int >:: value_type (studentInfo, 90 ));

StudentInfo. nID = 2;
StudentInfo. strName = "student_two ";
MapStudent. insert (map <StudentInfo, int >:: value_type (studentInfo, 80 ));

StudentInfo. nID = 2;
StudentInfo. strName = "student_three ";
MapStudent. insert (map <StudentInfo, int >:: value_type (studentInfo, 80 ));

Map <StudentInfo, int >:: iterator iter;
For (iter = mapStudent. begin (); iter! = MapStudent. end (); iter ++)
Cout <iter-> first. nID <iter-> first. strName <endl <iter-> second <endl;

Return 0;
}

 

<

Related Article

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.