C++ unordered_map自定义KEY用法以及insert无法覆盖解决办法

本文详细介绍了如何在C++中实现自定义KEY的重载判断和哈希值获取,包括使用boost库进行哈希计算,并解决插入无法覆盖问题的解决方案。重点在于提供一种高效的方法来处理键值对数据结构。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

对于自定义KEY需要重载==判断是否相等,用()获取hash值

struct	stream_order_key
{
	std::string instrument;
	ioption::TChnOrderLocalIDType orderLocalID;

	stream_order_key() : orderLocalID(0) {}

	bool operator==(const stream_order_key& s) const
	{
		return instrument==s.instrument && orderLocalID==s.orderLocalID;
	}

	size_t operator()(const stream_order_key& s) const
	{
		size_t seed = 0;
		boost::hash_combine(seed, boost::hash_value(s.instrument));
		boost::hash_combine(seed, boost::hash_value(s.orderLocalID));
		return seed;
	}

};



typedef std::unordered_map<<span style="font-family: Arial, Helvetica, sans-serif;">stream_order_key</span><span style="font-family: Arial, Helvetica, sans-serif;">, int, stream_order_key> stream_order_map;</span>

添加一个hash算法:

		inline size_t operator()(const T & ov) const
		{
			/// BKD HASH
			unsigned int seed = 131; // 31 131 1313 13131 131313 etc..
			unsigned int hash = 0;
			const char* str = ov.c_str();
			while (*str)
			{
				hash = hash * seed + (*str++);
			}

			return (hash & 0x7FFFFFFF);
		}


对于insert无法覆盖问题解决办法:

使用

stream_order_map order_map;

order_map[s] = a;

order_map[s] = b;

可以解决

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值