自定义结构体作为map的key

自定义结构体作为C/C++中的map,或是unordered_map的key值:

/**
 * self defined struct as the key of map in c++
 */
struct K {
    int n1, n2;
    K(int i, int j): n1(i), n2(j) {}
    // the operator < defines the operation used in map
    friend bool operator < (const struct K &k1, const struct K &k2);
};
 
inline bool operator < (const struct K &k1, const struct K &k2) {
    return k1.n1 < k2.n1 || (k1.n1==k2.n1 && k1.n2<k2.n2);
}
 
void test() {
    map<K, int> m;
    map<K, int>::iterator it;
    K k1(1, 1);
    m.insert(make_pair(k1, 2));    // insert the value
    it = m.find(k1);
    if (it!=m.end()) cout << it->second << endl;    // fetch the value
}

需要注意的是,当 struct  K 实习重载了operator < 时,只有 map<K, int> 等以 K 为key才可以调用重载后的 operator <。

如果是遇到 map<K*, int> 则不行。这点需要注意。
 

##################################

对于map来说, key必须是有序的, 也就是说, key与key之间必须能比较, 所以需要重载<号, 因此, 上述程序错误, 应该改为:

#include <iostream>
#include <string>
#include <map>
using namespace std;
 
struct Info
{
    string name;
    int score;
 
    bool operator< (const Info &x) const
    {
        return score < x.score;
    }
};
 
int main()
{
    Info a, b;
 
    a.name = "eric";
    a.score = 90;
 
    b.name = "cat";
    b.score = 85;
 
 
    map<Info, int> m;
    m[a] = 1;
    m[b] = 2;
 
    map<Info, int>::iterator it;
    for(it = m.begin(); it != m.end(); it++)
    {
        cout << it->first.name << endl;
    }
 
    return 0;
}

        运行正确, 结果为:
cat
eric

       OK, 本文先讨论到这里, 关键是要对map的“关键字有序”有足够的认识。
 

  • 2
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值