struct作为map的key

某些情况下,只用一个int或者一个string,无法满足需求,需要多个字段联合作为map的key,如何实现? 请看如下代码:

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


struct mapkey
{
        int sceneID;
        int teamID;

///>重载== 运算符
        bool operator == ( const mapkey& obj) const
        {
                if( sceneID == obj.sceneID && teamID == obj.teamID )
                {
                        return true; 
                }
                return false; 
        }

///>重载< 运算符
        bool operator < ( const mapkey& obj ) const
        {
                if( sceneID < obj.sceneID )
                {
                        return true; 
                }
                if( sceneID == obj.sceneID && teamID < obj.teamID )
                {
                        return true; 
                }
                return false;
        }
};


int main()
{
        std::map<mapkey, int> mapInfo;
        mapInfo.clear();


        mapkey stc;
        stc.sceneID = 1; 
        stc.teamID = 5; 
        mapInfo.insert( std::make_pair(stc, 1) );


        stc.sceneID = 2; 
        stc.teamID = 4; 
        mapInfo.insert( std::make_pair(stc, 5) );


        stc.sceneID = 2; 
        stc.teamID = 3; 
        mapInfo.insert( std::make_pair(stc, 6) );


        for( std::map<mapkey, int>::iterator it = mapInfo.begin(); it != mapInfo.end(); it++ )
        {
                printf("scenid:%llu, teamID:%llu, value:%d\n", it->first.sceneID, it->first.teamID, it->second);
        }


        stc.sceneID = 2;
        stc.teamID = 3; 
        std::map<mapkey, int>::iterator itFind = mapInfo.find( stc );
        if( itFind == mapInfo.end() )
        {
                printf("cannot find key, sceneID:%llu, teamID:%llu\n", stc.sceneID, stc.teamID);
        }
        else
        {
                printf("find key success, sceneID:%llu, teamID:%llu\n", stc.sceneID, stc.teamID);
        }

        stc.sceneID = 2;
        stc.teamID = 8;
        itFind = mapInfo.find( stc );
        if( itFind == mapInfo.end() )
        {
                printf("cannot find key, sceneID:%llu, teamID:%llu\n", stc.sceneID, stc.teamID);
        }
        else
        {
                printf("find key success, sceneID:%llu, teamID:%llu\n", stc.sceneID, stc.teamID);
        }

}

编译:

$ g++ -g -o hello stckey.cpp 


运行:

$  ./hello


输出如下:

$ ./hello 

scenid:1, teamID:5, value:1
scenid:2, teamID:3, value:6
scenid:2, teamID:4, value:5

find key success, sceneID:2, teamID:3
cannot find key, sceneID:2, teamID:8





  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值