某些情況下,只用一個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: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