当在STL应用中,我们常常会使用到结构体,这就需要我们对特定要求的运算符进行重载。例如在,STL中的排序都是默认使用小于号来排序。因此,在对结构体排序时,我们就需要重载小于号。
举例:
#include
using namespace std;
//学生信息
typedef struct tagStudentInfo
{
 int nID;
 string strName;
 bool operator <(const tagStudentInfo &A) const
 {
  if (nID < A.nID) return true;  //先比较nID
  if (nID == A.nID) return strName.compare(A.strName) < 0;   //nID相同时,再比较strName
  return false;
 }
}StudentInfo,*pstudentInfo;
int main()
{
 //用学生信息映射分数
 map
StudentInfo studentInfo;
 studentInfo.nID = 1;
 studentInfo.strName = "student_one";
 mapStudent.insert(map
 studentInfo.nID = 2;
 studentInfo.strName = "student_two";
 mapStudent.insert(map
 studentInfo.nID = 2;
 studentInfo.strName = "student_three";
 mapStudent.insert(map
 map
 for (iter=mapStudent.begin(); iter!=mapStudent.end(); iter++)
  cout << iter->first.nID << iter->first.strName << endl << iter->second << endl;
 return 0;
}