在c++中用到map时,如果key是自定义的struct,那么需要自己定义比较函数。因为只有基本类型有默认的比较方法。
typedef struct myKey
{
int nId;
int nVersion;
int nNote;
}myKey;
///自定义map的value
typedef struct myValue
{
string strText;
}myValue;
struct cmp_key
{
bool operator()(const myKey &k1,const myKey &k2) const
{
if(k1.nId != k2.nId)
{
return k1.nId < k2.nId;
}
if(k1.nVersion != k2.nVersion)
{
return k1.nVersion < k2.nVersion;
}
if(k1.nNote != k2.nNote)
{
return k1.nNote < k2.nNote;
}
return false;
}
};
int _tmain(int argc, _TCHAR* argv[])
{
map mymap;
myKey k1;
k1.nId = 1;
k1.nVersion = 2;
k1.nNote = 3;
myValue v1;
v1.strText = "k1: id=1 version=2 note=3";
myKey k2;
k2.nId = 2;
k2.nVersion = 2;
k2.nNote = 3;
myValue v2;
v2.strText = "k1: id=2 version=2 note=3";
myKey k3;
k3.nId = 2;
k3.nVersion = 2;
k3.nNote = 5;
myValue v3;
v3.strText = "k1: id=2 version=2 note=5";
mymap[k1] = v1;
mymap[k2] = v2;
mymap[k3] = v3;
for(auto it = mymap.begin(); it != mymap.end(); ++it)
{
cout << it->second.strText.c_str() << endl;
}
return 0;
}
输出:
k1: id=1 version=2 note=3
k1: id=2 version=2 note=3
k1: id=2 version=2 note=5
对value排序的话,用vector代替。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)