一、vector
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 | void TestVector() { cout << "begin create vector" << endl; int iSize = 10000000; vector< int > test_vec; for ( int i = 0; i < iSize; i++) { test_vec.push_back(i); } cout << "create vector end" << endl; Sleep(2*1000); cout << "clear vector" << endl; test_vec.clear(); cout << "clear vector end" << endl; Sleep(1*1000); cout << "after clear new data come if the size bigger" << endl; for ( int i = 0; i < iSize; i++) { test_vec.push_back(i); } cout << "new data push_back end" << endl; Sleep(1*1000); cout << "swap vector" << endl; { vector< int > tmp_vec; test_vec.swap(tmp_vec); } cout << "swap vector end" << endl; Sleep(1*1000); } |
测试过程:
![](https://i-blog.csdnimg.cn/blog_migrate/58218c6c9766cc171a49f1d108bfb27f.png)
![](https://i-blog.csdnimg.cn/blog_migrate/8442baa5237ff04b95b6b51bfba240f3.png)
![](https://i-blog.csdnimg.cn/blog_migrate/00fad8279ba553dc3406ecaca815464d.png)
![](https://i-blog.csdnimg.cn/blog_migrate/4756b00e9c08680d654a3c2e079182da.png)
![](https://i-blog.csdnimg.cn/blog_migrate/75655d9a7965c1638ab31b2656bf84a8.png)
![](https://i-blog.csdnimg.cn/blog_migrate/a9884ac8726fcdd095cdc56dc98949e6.png)
![](https://i-blog.csdnimg.cn/blog_migrate/151788a6e6c5920a0a057e0516ebcf78.png)
![](https://i-blog.csdnimg.cn/blog_migrate/164f13ee9f4d2472a3ebe1cdbf55bf1d.png)
![](https://i-blog.csdnimg.cn/blog_migrate/bf7e80aa5ed9957a92cb20bea2e1404b.png)
![](https://i-blog.csdnimg.cn/blog_migrate/b34187421d65c915e4d0ef791171cd10.png)
结论:
1. vector clear 之后,内存没有释放,但在下次分配时会复用该块内存。
2. vector swap 空数据之后,会释放内存。
二、map
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 | void TestMap() { cout << "begin create map" << endl; int iSize = 1000000; map< int , int > test_map; for ( int i = 0; i < iSize; i++) { test_map[i] = i; } cout << "create map end" << endl; Sleep(2*1000); cout << "clear map" << endl; test_map.clear(); cout << "clear map end" << endl; getchar (); cout << "swap map" << endl; { map< int , int > tmp_map; test_map.swap(tmp_map); } cout << "swap map end" << endl; getchar (); } |
测试过程:
![](https://i-blog.csdnimg.cn/blog_migrate/6382dc9da91f1fafa03d30e23fc8a739.png)
![](https://i-blog.csdnimg.cn/blog_migrate/de3eece832bd516adad9d987f9e846c9.png)
![](https://i-blog.csdnimg.cn/blog_migrate/b2976bec982096a2c55137e8c0aeaab0.png)
![](https://i-blog.csdnimg.cn/blog_migrate/9a06e1915da01f8f862037153caa4b7b.png)
![](https://i-blog.csdnimg.cn/blog_migrate/0c829544f02428f59f97b5e96be4900e.png)
![](https://i-blog.csdnimg.cn/blog_migrate/5d43963a1e56afb1ec3c73bf5d437141.png)
![](https://i-blog.csdnimg.cn/blog_migrate/996d5edc842df8a2e68a2eb878aece5f.png)
结论:
1. map clear 之后,会释放内存。
2. map swap 空数据之后,会释放内存。
https://www.cnblogs.com/SZxiaochun/p/8432817.html