【C++】自定义结构体作为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> 则不行。这点需要注意。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值