c++ map是有序还是无序的_c++ unorder_map的用法
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;
}
總結
以上是生活随笔為你收集整理的c++ map是有序还是无序的_c++ unorder_map的用法的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 5000mAh电池!三星入门机型开启首销
- 下一篇: s3c2440移植MQTT