博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

map自定义结构体作为key

Posted on 2018-05-07 16:38  chixinfushui  阅读(3475)  评论(0编辑  收藏  举报


#include <stdio.h>
#include <string>
#include <map>

using namespace std;
typedef struct mystr
{
  int t;
};
typedef struct _MAPKEY
{
  int ikey;
  string strkey;
  mystr mt;
  bool operator < (const _MAPKEY& mapkey)const
  {
    if (mt.t ==0)
    {
      return strkey < mapkey.strkey;
    }
    return strkey < mapkey.strkey;
  }
}MAPKEY;
map<MAPKEY, int>mymap;

int main()
{
  MAPKEY m1,m2;
  m1.ikey = 2;
  m1.strkey = "hello";
  m2.ikey = 23;
  m2.strkey = "main";
  mymap.insert(make_pair(m1,20));
  mymap.insert(make_pair(m2,1));
  map<MAPKEY,int>::iterator itt = mymap.begin();
  itt = mymap.find(m2);
  MAPKEY TM = itt->first;
  return 0;
}