测试代码

在C++ STL的map中保存map:

 1 #include <iostream>
 2 #include <map>
 3 #include <string>
 4 
 5 using  namespace std;
 6 
 7 int main()
 8 {
 9     std::map<int, std::map<std::string, int>* > test_map;
10     std::map<std::string, int>* map_01;
11     for(int i=0; i<10; ++i){
12         map_01 = new std::map<std::string, int>;
13         test_map.insert(make_pair(i, map_01));
14     }   
15 
16     for(std::map<int, std::map<std::string, int>* >::iterator it=test_map.begin(); it!=test_map.end(); ++it){
17         std::cout << "first " << it->first << std::endl;
18     }   
19     
20     for(std::map<int, std::map<std::string, int>* >::iterator it = test_map.begin();
21         it != test_map.end(); ++it){
22         map_01 = it->second;
23         delete map_01;
24         map_01 = NULL;
25     }   
26 
27     return 0;
30 }
31 
32 root@u18:~/cp/test# g++ map.cpp  -g -Wall
33 root@u18:~/cp/test# ./a.out
34 first 0
35 first 1
36 first 2
37 first 3
38 first 4
39 first 5
40 first 6
41 first 7
42 first 8
43 first 9
44 root@u18:~/cp/test#  valgrind --tool=memcheck ./a.out
45 ==21868== Memcheck, a memory error detector
46 ==21868== Copyright (C) 2002-2011, and GNU GPL'd, by Julian Seward et al.
47 ==21868== Using Valgrind-3.7.0 and LibVEX; rerun with -h for copyright info
48 ==21868== Command: ./a.out
49 ==21868== 
50 first 0
51 first 1
52 first 2
53 first 3
54 first 4
55 first 5
56 first 6
57 first 7
58 first 8
59 first 9
60 ==21868== 
61 ==21868== HEAP SUMMARY:
62 ==21868==     in use at exit: 0 bytes in 0 blocks
63 ==21868==   total heap usage: 20 allocs, 20 frees, 960 bytes allocated
64 ==21868== 
65 ==21868== All heap blocks were freed -- no leaks are possible
66 ==21868== 
67 ==21868== For counts of detected and suppressed errors, rerun with: -v
68 ==21868== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 2 from 2)
69 root@u18:~/cp/test#
原文地址:https://www.cnblogs.com/chris-cp/p/4617463.html