一、自定义key的结构体
typedef struct ST_PlanFileKey
{
int ctIndex = -1;
int planIndex = -1;
bool operator <(const ST_PlanFileKey& data) const
{
return planIndex < data.planIndex;
}
} PlanFileKey;
二、测试代码
PlanFileKey fileKey;
std::map<PlanFileKey, int> testMap;
fileKey.ctIndex = 0;
fileKey.planIndex = 0;
testMap[fileKey] = 1;
fileKey.planIndex = 2;
testMap[fileKey] = 2;
fileKey.planIndex = 3;
testMap[fileKey] = 3;
//
fileKey.ctIndex = 1;
fileKey.planIndex = 2;
if (testMap.end() != testMap.find(fileKey))
{
qDebug() << "" << testMap[fileKey]; //qt的输出,类似于std::out
}
1.结果
大家可以猜测下,是否会有输出?
实际这个会输出2,那也就是说,fileKey(ctIndex=1,planIndex=2)的key匹配到了fileKey(ctIndex=0,planIndex=2)的值,神不神奇?
答案:调用find的时候,会去执行operator <函数,对于自定义key有多个值的时候,必须每个值都进行判断,有个优先级。如下修改即可
bool operator <(const ST_PlanFileKey& data) const
{
if (ctIndex != data.ctIndex)
{
return ctIndex < data.ctIndex;
}
return planIndex < data.planIndex;
}
三、测试代码2
std::pair<int, int> fileKey;
std::map<std::pair<int, int>, int> testMap;
fileKey.first = 0;
fileKey.second = 0;
testMap[fileKey] = 1;
fileKey.second = 2;
testMap[fileKey] = 2;
fileKey.first = 1;
if (testMap.end() != testMap.find(fileKey))
{
qDebug() << "" << testMap[fileKey];
}
1.结果
这边并不输出任何值,说明没有匹配上。