-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathUnorderedMap.cpp
More file actions
82 lines (67 loc) · 2.05 KB
/
UnorderedMap.cpp
File metadata and controls
82 lines (67 loc) · 2.05 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
// cppcheck-suppress-file [unreadVariable,unusedVariable,redundantInitialization]
// HashMap: Collection of key-value pairs that are hashed by their keys where no two pairs have same keys.
/**
* std::unordered_map
*
* <vector>
*/
#include <iostream>
#include <string>
#include <unordered_map>
#include <vector>
namespace {
void run() {
std::cout << "\n--- std::unordered_map Example ---\n";
// 1) Init
std::unordered_map<std::string, int> m_map{
{"k_1", 1}, {"k_2", 2}, {"k_3", 3}};
// 2) Modifiers
m_map.insert({"k_4", 4});
std::pair<std::string, int> newElem1 = {"k_5", 0};
m_map.insert(newElem1);
std::string m_key = "k_6";
int m_value = 99;
auto newElem2 = std::make_pair(m_key, m_value);
m_map.insert(newElem2);
auto m_map2 = m_map;
for (auto it = m_map.begin(); it != m_map.end();) {
it = m_map.erase(it);
}
for (const std::pair<const std::string, int>& e : m_map) {
std::cout << "[" << e.first << "," << e.second << "]" << " ";
}
std::cout << std::endl;
m_map2.insert_or_assign("k_6", 8888); // WORK
auto pos = m_map2.find("k_6");
if (pos != nullptr) {
m_map2.insert(std::make_pair(
"k_6", 9999)); // cannot reassign if this pair already existed
}
// 3) Lookup
pos = m_map.find("k_1");
std::cout << (pos != nullptr ? "true" : "false") << std::endl;
for (auto const& [k, v] : m_map2) {
std::cout << "[" << k << "," << v << "]" << " ";
}
std::cout << std::endl;
// 4) Make fun
std::vector<std::string> keys{};
for (auto const& [k, v] : m_map2) {
keys.push_back(k);
}
std::cout << "Keys: " << std::endl;
for (auto const& k : keys) {
std::cout << k << " ";
}
std::cout << std::endl;
}
} // namespace
#include "ExampleRegistry.h"
class UnorderedMap : public IExample {
public:
std::string group() const override { return "core/container"; }
std::string name() const override { return "UnorderedMap"; }
std::string description() const override { return ""; }
void execute() override { run(); }
};
REGISTER_EXAMPLE(UnorderedMap, "core/container", "UnorderedMap");