#include <iostream>
#include <map>
using namespace std;
class Test_t {
private:
int a;
public:
Test_t(int a)
{
this->a = a;
}
~Test_t()
{
cout << "destory Test_t" << endl;
}
void show(void)
{
cout << "a = " << a << endl;
}
};
typedef map<int, Test_t *> Test_map_t;
Test_map_t g_test_map;
void init_map(void)
{
Test_t *t1 = new Test_t(1);
Test_t *t2 = new Test_t(2);
pair<Test_map_t::iterator, bool> ret;
ret = g_test_map.insert(pair<int, Test_t *>(1, t1));
if (!ret.second) {
cout << "Failed to insert t1 into 1" << endl;
}
ret = g_test_map.insert(pair<int, Test_t *>(2, t2));
if (!ret.second) {
cout << "Failed to insert t2 into 2" << endl;
}
/* example: failed to insert */
ret = g_test_map.insert(pair<int, Test_t *>(1, t2));
if (!ret.second) {
cout << "Failed to insert t2 into 1" << endl;
}
}
void show_map(void)
{
Test_map_t::iterator iter = g_test_map.begin();
while (iter != g_test_map.end()) {
cout << iter->first << ": ";
iter->second->show();
++iter;
}
}
void remove_map(void)
{
Test_map_t::iterator iter = g_test_map.begin();
cout << "size = " << g_test_map.size() << endl;
while (iter != g_test_map.end()) {
cout << iter->first << " is removed" << endl;
delete iter->second;
g_test_map.erase(iter);
++iter;
}
cout << "size = " << g_test_map.size() << endl;
}
void erase_map(void)
{
cout << "size = " << g_test_map.size() << endl;
while (!g_test_map.empty()) {
cout << (g_test_map.begin())->first << " is erased" << endl;
delete (g_test_map.begin())->second;
g_test_map.erase(g_test_map.begin());
}
cout << "size = " << g_test_map.size() << endl;
}
Test_t *find_test_by_index(int index)
{
auto iter = g_test_map.find(index);
//Test_map_t::iterator iter = g_test_map.find(index);
if (iter == g_test_map.end()) {
return nullptr;
}
return iter->second;
}
int main(int argc, char *const argv[])
{
Test_t *t = nullptr;
init_map();
show_map();
cout << "find index = 2" << endl;
t = find_test_by_index(2);
if (nullptr != t) {
t->show();
}
cout << "OK" << endl;
remove_map();
return 0;
}
result:
$ g++ -std=c++11 test.cpp
$ ls
a.out test.cpp
$ ./a.out
Failed to insert t2 into 1
1: a = 1
2: a = 2
find index = 2
a = 2
OK
size = 2
1 is removed
destory Test_t
2 is removed
destory Test_t
size = 0