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; 
}

  • 4
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值