近日被问到Map的key为自定义结构体的情况,由于从未使用,特此测试验下,运行及总结情况如下。
#include "stdafx.h"
#include <map>
using namespace std;
struct A
{
int a;
bool operator <(const A& rhs) const {
return a < rhs.a;
}
};
struct B
{
int b;
};
#include <iostream>
int main()
{
A sa1;
sa1.a = 10;
A sa2;
sa2.a = 20;
map<A, int> mp;
mp.insert(pair<A, int>(sa1, 30));
mp.insert(pair<A, int>(sa2, 60));
cout << mp[sa1] << endl;
cout << mp[sa2] << endl;
map<A, int>::iterator iter = mp.find(sa1);
if (iter != mp.end())
{
cout << "find sa1 := " << iter->second << endl;
}
B sb1;
sb1.b = 100;
B sb2;
sb2.b = 200;
map<B*, int> pm;
pm.insert(pair<B*, int>(&sb1, 1200));
pm.insert(pair<B*, int>(&sb2, 2400));
cout << pm[&sb1] << endl;
cout << pm[&sb2] << endl;
sb2.b = 600;
map<B*, int>::iterator bIter = pm.find(&sb2);
if (bIter != pm.end())
{
cout << "find &sb2 := " << bIter->second <<endl;
}
return 0;
}
结论:
A: Key用结构体变量,需要重写排序函数。如果排序函数出错,整个Map序列错乱。
B: Key用结构体变量,不用担心键值被修改带来的影响。
C: 用指针,无需重写排序算法
D: 用指针,可以修改结构体的值,value的值不受影响。Find也不会受影响。
E: 用指针,有被delete的风险