-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathdraft_map.cpp
More file actions
106 lines (89 loc) · 2.62 KB
/
Copy pathdraft_map.cpp
File metadata and controls
106 lines (89 loc) · 2.62 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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
#include <iostream>
#include <map>
#include <vector>
#include <string>
#include <set>
#include <tuple>
template <typename Map>
void print_map(Map &x)
{
std::cout << "{";
for (auto &y : x)
{
std::cout << y.first << ":" << y.second << ", ";
}
std::cout << "}\n";
}
void test_map_constructor()
{
// https://en.cppreference.com/w/cpp/container/map/map
std::cout << "\n# test_map_constructor\n";
std::map<std::string, int> z0;
z0["a"] = 2;
z0["ab"] = 23;
z0["abb"] = 233;
std::cout << "default constructor: ";
print_map(z0);
std::map<std::string, int> z1(z0.find("ab"), z0.end());
std::cout << "iterator constructor: ";
print_map(z1);
std::map<std::string, int> z2(z0);
std::cout << "copy constructor: ";
print_map(z2);
std::map<std::string, int> z3(std::move(z0));
std::cout << "move constructor: ";
print_map(z3);
std::cout << "\t the original map after moving: ";
print_map(z0);
std::map<std::string, int> z4{{"a", 2}, {"ab", 23}, {"abb", 233}};
std::cout << "initializer list constructor: ";
print_map(z4);
}
class MyClass00
{
};
void test_pointer_as_key()
{
std::cout << "\n# test_pointer_as_key\n";
MyClass00 x0, x1, x2;
std::map<MyClass00 *, std::string> z0;
z0[&x0] = "0x&";
z0[&x1] = "1x&";
z0[&x2] = "2x&";
//the duty of a function: make sure the return value is valid, NOT check that the received pointer is valid
std::cout << "dict[address of x0]: " << z0[&x0] << std::endl;
std::cout << "dict[address of x1]: " << z0[&x1] << std::endl;
std::cout << "dict[address of x2]: " << z0[&x2] << std::endl;
}
void test_map_iterator()
{
std::cout << "\n# test_map_iterator\n";
int x0 = 2, x1 = 23, x2 = 233;
std::map<int *, int> z0{{&x0, x0}, {&x1, x1}, {&x2, x2}};
auto tmp0 = z0.find(&x2);
if (tmp0 != z0.end())
{
std::cout << "&x2: " << &x2 << std::endl;
std::cout << "map.find(&x2)->first: " << tmp0->first << std::endl;
std::cout << "map.find(&x2)->second: " << tmp0->second << std::endl;
}
}
void test_tuple_as_key()
{
std::cout << "\n# test_tuple_as_key\n";
using tuple_ii = std::tuple<int, int>;
std::map<tuple_ii, std::string> z0;
z0[tuple_ii(2, 33)] = "233";
std::cout << "map.find(tuple(2,33)): " << z0[tuple_ii(2, 33)] << std::endl;
}
// g++ draft_map.cpp -std=c++11 -o tbd00.exe
int main(int argc, char *argv[])
{
std::cout << "# draft00_vector_set_map.cpp" << std::endl;
test_map_constructor();
test_pointer_as_key();
test_map_iterator();
test_tuple_as_key();
std::cout << std::endl;
return 0;
}