C++ unordered_map使用自定义类型作为键值

unordered_map

unordered_map 的创建及基本用法如下

#include<unordered_map>
// 声明
unordered_map<int, string> map;
// insert插入
map.insert(make_pair(1, "x"));
map.insert(make_pair(1, "g"));  // 用insert插入的键如果存在则跳过,此时map[1]仍为"x"
// 下标插入
map[2]="g";  // 如果值是数字,可以直接map[key]++,若key原来不存在,则建立key:1键值对
map[2]="z";  // 用下标插入的键如果存在的话会覆盖之前的值,此时map[2]为"z"
// 判断键存在
bool exist = (map.find(2) != map.end());
// 访问
unordered_map<int, string>::iterator iter=map.find(2);
cout << iter->first << "  " << iter->second << endl;
// 删除键值对
map.erase(2);
// 遍历
for(auto& m:map){
	cout<<m.first<<':'<<m.second<<endl;
	}

下面是使用自定义类型作为unordered_map的key的方法之一,在这个情境中,我们需要将点对象(x,y)作为键值,让其对应一个整型值,为此,需要为自定义点类型实现两个方法,一是给出判断不同点对象相等的标准,二是给出点对象的hash函数。

这里采用的是(我目前也不太懂),大概是在点结构体中实现了判断不同点对象是否相等的方法,然后又创建了一个结构体(用来做hash),将它传入unordered_map的初始化中。

#include <unordered_map>

using namespace std;

struct point
{
    int x,y;
    
    point(){
        x=y=0;
    }
    bool operator == (const point& p) const{
        return x==p.x&&y==p.y;
    }
};
struct hash_point{
	size_t operator()(const point & p) const{
		return hash<int>()(p.x) ^ hash<int>()(p.y);
	}
};
int main()
{
    unordered_map<point, int, hash_point> setp;
}
  • 3
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值