vector、map 内存释放

一、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);

}

测试过程:

 

 

 

 

结论:

  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<intint> 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<intint> tmp_map;

        test_map.swap(tmp_map);

    }

    cout << "swap map end" << endl;

    getchar();

}

测试过程:

 

 

 

结论:

  1. map clear 之后,会释放内存。

  2. map swap 空数据之后,会释放内存。

https://www.cnblogs.com/SZxiaochun/p/8432817.html

  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值