//
// Created by william on 2021/8/8.
//
#include "base.h"
struct Key
{
std::string first;
std::string second;
};
struct KeyHash
{
std::size_t operator()(const Key& k) const
{
return std::hash<:string>()(k.first) ^ (std::hash<:string>()(k.second)) << 1;
}
};
struct KeyEqual
{
bool operator()(const Key& lhs, const Key& rhs) const
{
return lhs.first == rhs.first && lhs.second == rhs.second;
}
};
struct Foo
{
Foo(int val_) :
val(val_) {}
int val;
bool operator==(const Foo& rhs) const { return val == rhs.val; }
};
namespace std
{
template <>
struct hash
{
std::size_t operator()(const Foo& f) const
{
return std::hash{}(f.val);
}
};
} // namespace std
void unorderedMapTest()
{
// å建ä¸ä¸ª string ç unordered_map ï¼æ å°å° string ï¼
std::unordered_map<:string std::string> u = {
{ "RED", "#FF0000" },
{ "GREEN", "#00FF00" },
{ "BLUE", "#0000FF" }
};
// è¿ä»£å¹¶æå° unordered_map çå
³é®åå¼
for (const auto& n : u)
{
std::cout << "Key:[" << n.first << "] Value:[" << n.second << "]\n";
}
// æ·»å æ°å
¥å£å° unordered_map
u["BLACK"] = "#000000";
u["WHITE"] = "#FFFFFF";
// ç¨å
³é®è¾åºå¼
std::cout << "The HEX of color RED is:[" << u["RED"] << "]\n";
std::cout << "The HEX of color BLACK is:[" << u["BLACK"] << "]\n";
// é»è®¤æé 彿°ï¼ç©º unordered_map
std::unordered_map<:string std::string> m1;
// å表æé 彿°
std::unordered_map m2 = {
{ 1, "foo" },
{ 3, "bar" },
{ 2, "baz" },
};
// å¤å¶æé 彿°
std::unordered_map m3 = m2;
// ç§»å¨æé 彿°
std::unordered_map m4 = std::move(m2);
// èå´æé 彿°
std::vector<:pair>, int>> v = { {0x12, 1}, {0x01,-1} };
std::unordered_map<:bitset>, double> m5(v.begin(), v.end());
// 带å®å¶ Key ç±»åçæé 彿°çé项 1
// å®ä¹ KeyHash ä¸ KeyEqual ç»æä½å¹¶å¨æ¨¡æ¿ä¸ä½¿ç¨å®ä»¬
std::unordered_map m6 = {
{ {"John", "Doe"}, "example"},
{ {"Mary", "Sue"}, "another"}
};
// 带å®å¶ Key ç±»åçæé 彿°çé项 2
// 为 class/struct å®ä¹ const == è¿ç®ç¬¦å¹¶äº std å½å空é´ç¹å std::hash ç»æä½
std::unordered_map m7 = {
{ Foo(1), "One"}, { 2, "Two"}, { 3, "Three"}
};
// é项 3 ï¼ç¨ lambdas
// 注æå¿
é¡»å°åå§æ¡¶æ°ä¼ éç»æé 彿°
struct Goo {int val; };
auto hash = [](const Goo &g){ return std::hash{}(g.val); };
auto comp = [](const Goo &l, const Goo &r){ return l.val == r.val; };
std::unordered_map m8(10, hash, comp);
}