map、vector内存释放

1、vecotr的内存问题:

vector对象存在栈中,栈中是vector所存数据的地址,而数据保存在堆中。对于存储数据量较大的变量,vector存在内存问题。在不使用时,可以进行清理,清理vector内存的方法是定义一个空的vector,使用空的vector释放内存。

vector<int> tmp; //空
 
vec.swap(tmp); //待释放的vecotr变量

2、map的内存释放:

map的释放也可以参考上面的vector的方法,但map的释放不是立即释放的,map会根据内存情况自己释放,若要立即释放如下:

#include <iostream>
#include <map>
#include <malloc.h>
#include <string>
int main()
{
 	map<string, int> test;
	test["Alice"] = 3;
	test["Cindy"] = 5;
	test["Bob"] = 7;
    map<std::string, int>().swap(test);
    malloc_trim(0);
      
}
posted @ 2022-05-30 11:08  萧海~  阅读(520)  评论(0编辑  收藏  举报