C++中自定义结构体作为map的主键

在一个需求中,如果其map的主键是一个自定义的结构题,会和简单的如string类型,int类型的结构体作为主键有什么不一样呢?我们来试一试.我的需求是按照我想要的维度来对我自定义的结构体进行排序.

1.版本1-不重载<操作符的时候无法编译通过

#include <iostream>
#include <map>
using namespace std;

typedef struct testStruct{
   int a; 
   int b;
}TestStruct;

map<TestStruct,int> g_mapTest;
int main(){
    TestStruct objTestA;
    objTestA.a = 1;
    objTestA.b = 2;
    g_mapTest[objTestA]=1;
}

2.版本2-重载<操作符时可以编译通过但是不能达到预期效果

#include <iostream>
#include <map>
using namespace std;

typedef struct testStruct{
   int a; 
   int b;
   bool operator< (const testStruct& A)const{
      if(this->a < A.a)
         return true;
      else
         return false;
   }
}TestStruct;

map<TestStruct,int> g_mapTest;
int main(){
    TestStruct objTestA;
    objTestA.a = 1;
    objTestA.b = 1;
    g_mapTest[objTestA]=1;
    objTestA.a = 1;
    objTestA.b = 2;
    g_mapTest[objTestA]=1;
    cout << "g_mapTest.size() is " << g_mapTest.size() << endl; 
}

3.版本3-重载<操作符时可以编译通过能达到预期效果

#include <iostream>
#include <map>
using namespace std;

typedef struct testStruct{
   int a; 
   int b;
   bool operator< (const testStruct& A)const{
      if(this->a < A.a)
         return true;
      else if(this->a == A.a && this->b < A.b)
         return true;
      else
         return false;
   }
}TestStruct;

map<TestStruct,int> g_mapTest;
int main(){
    TestStruct objTestA;
    objTestA.a = 1;
    objTestA.b = 1;
    g_mapTest[objTestA]=1;
    objTestA.a = 1;
    objTestA.b = 2;
    g_mapTest[objTestA]=1;
    cout << "g_mapTest.size() is " << g_mapTest.size() << endl; 
}


版权声明:本文为Edidaughter原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。