1、unorder_map与map不同:map的KEY值是有序的,而unorder_map则是无序的;
2、unorder_map自定义的KEY值时需要注意思下面两点:
· KEY为一个类时,需要重载==符号;
· 需要自定义一个HASH类,至于为什么,自己百度找原因
下面贴上unorder_map的两类使用方法
第一种:
#include
#include
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
{
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()(k.m_strName))^(hash()(k.m_iAge) << 1));
}
};
int _tmain(int argc, _TCHAR* argv[])
{
std::unordered_map info;
};
第二种:
#include
#include
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()(k.m_strName)) ^ (hash()(k.m_iAge) << 1));
}
};
int _tmain(int argc, _TCHAR* argv[])
{
std::unordered_map info;
}