c++ unorder_map的用法

1、unorder_map与map不同:map的KEY值是有序的,而unorder_map则是无序的;

2、unorder_map自定义的KEY值时需要注意思下面两点:

      · KEY为一个类时,需要重载==符号;

      · 需要自定义一个HASH类,至于为什么,自己百度找原因

下面贴上unorder_map的两类使用方法

第一种:

#include <unordered_map>
#include <string>
using namespace std;


class Node
{
public:
	Node();
	~Node();

	bool operator==(const Node &n) const;
public:
	std::string m_strName;
	int m_iAge;
};

Node::Node() :m_iAge(0)
{
}

Node::~Node()
{
}

bool Node::operator==(const Node & n) const 
{
	if (n.m_iAge==m_iAge && m_strName==n.m_strName)
	{
		return true;
	}
	return false;
}

template <>
struct hash<Node>
{
	std::size_t operator()(const Node& k) const
	{
		using std::size_t;
		using std::hash;
		using std::string;
		// Compute individual hash values for first,
		// second and third and combine them using XOR
		// and bit shifting:
		return ((hash<string>()(k.m_strName))^(hash<int>()(k.m_iAge) << 1));
	}
};

int _tmain(int argc, _TCHAR* argv[])
{
	std::unordered_map<Node, int> info;
};

第二种:

#include <unordered_map>
#include <string>
using namespace std;


class Node
{
public:
	Node();
	~Node();

	bool operator==(const Node &n) const;
public:
	std::string m_strName;
	int m_iAge;
};

Node::Node() :m_iAge(0)
{
}

Node::~Node()
{
}

bool Node::operator==(const Node & n) const 
{
	if (n.m_iAge==m_iAge && m_strName==n.m_strName)
	{
		return true;
	}
	return false;
}

struct KeyHasher
{
	std::size_t operator()(const Node& k) const
	{
		using std::size_t;
		using std::hash;
		using std::string;
		return ((hash<string>()(k.m_strName)) ^ (hash<int>()(k.m_iAge) << 1));
	}
};

int _tmain(int argc, _TCHAR* argv[])
{
	std::unordered_map<Node, int, KeyHasher> info;
} 




  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值