map基本的使用;
#include <iostream>
#include <map>
using namespace std;
int main()
{
map<char ,pair<int,int> > myMap;
cout << myMap.size ()<<endl; //输出是0,调用默认构造初始化
myMap.insert (pair<char,pair<int,int> >('a',pair<int,int>(120,230)));
pair<int,int> value1 = myMap['a'];
cout << value1.first<< " " << value1.second<<endl;
myMap.insert (make_pair('a',make_pair(121,231)));
pair<int,int> value2 = myMap['a'];
cout << value2.first<< " " << value2.second<<endl;//值并未改变
myMap.insert(map<char,pair<int,int> >::value_type('a',pair<int,int>(122, 232)));
pair<int,int> value3 = myMap['a'];
cout<<value3.first<<" "<<value3.second<<endl;
myMap['a'] = pair<int,int>(123,233);
cout << myMap.size ()<<endl; //输出是1,调用默认构造初始化
pair<int,int> value4 = myMap['a'];
cout << value4.first<< " " << value4.second<<endl;
cout << "myMap.size ()="<< myMap.size () <<endl;
myMap.clear();
cout << "myMap.size ()="<< myMap.size () <<endl;
cout << value4.first<< " " << value4.second<<endl;
map<char,pair<int,int> >().swap(myMap);
cout << "myMap.size ()="<< myMap.size () <<endl;
cout << value4.first<< " " << value4.second<<endl;
return 0;
}
内存并未释放干净;vector使用swap可以释放内存,map则不可以,貌似而STL保留了这部分内存,下次分配的时候会复用这块内存。
==12807== Memcheck, a memory error detector
==12807== Copyright (C) 2002-2015, and GNU GPL'd, by Julian Seward et al.
==12807== Using Valgrind-3.11.0 and LibVEX; rerun with -h for copyright info
==12807== Command: ./a.out
==12807== Parent PID: 1055
==12807==
==12807==
==12807== HEAP SUMMARY:
==12807== in use at exit: 72,704 bytes in 1 blocks
==12807== total heap usage: 3 allocs, 2 frees, 73,776 bytes allocated
==12807==
==12807== 72,704 bytes in 1 blocks are still reachable in loss record 1 of 1
==12807== at 0x4C2DB8F: malloc (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==12807== by 0x4EC3EFF: ??? (in /usr/lib/x86_64-linux-gnu/libstdc++.so.6.0.21)
==12807== by 0x40106C9: call_init.part.0 (dl-init.c:72)
==12807== by 0x40107DA: call_init (dl-init.c:30)
==12807== by 0x40107DA: _dl_init (dl-init.c:120)
==12807== by 0x4000C69: ??? (in /lib/x86_64-linux-gnu/ld-2.23.so)
==12807==
==12807== LEAK SUMMARY:
==12807== definitely lost: 0 bytes in 0 blocks
==12807== indirectly lost: 0 bytes in 0 blocks
==12807== possibly lost: 0 bytes in 0 blocks
==12807== still reachable: 72,704 bytes in 1 blocks
==12807== suppressed: 0 bytes in 0 blocks
==12807==
==12807== For counts of detected and suppressed errors, rerun with: -v
==12807== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 0 from 0)