您的位置:首页 > 其它

struct作为map的key

2016-08-12 15:23 274 查看
某些情况下,只用一个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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: