C++ 使用Swap收缩内存空间

    C++中,Swap用于交换容器内容。

#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;

void print(int val)
{
    cout << val << " ";
}

int main()
{
    vector<int> v1 = {1,2,3,4,5};
    vector<int> v2 = {6,7,8,9};

    v1.swap(v2);

    cout << "v1 = ";
    for_each(v1.begin(), v1.end(), print);
    cout << endl;
    cout << "v2 = ";
    for_each(v2.begin(), v2.end(), print);

    getchar();
    return 0;
}

    容器v1和v2的内容交换。执行结果如下:

  

    在实际应用中,Swap常用于收缩内存空间。

#include<iostream>
#include<vector>
using namespace std;

int main()
{
    vector<int> v;
    for (int i = 0; i < 10000; i++)
    {
        v.push_back(i);
    }

    cout << "size = " << v.size() << endl;
    cout << "capacity = " << v.capacity() << endl << endl;


    v.resize(3); //重置大小
    cout << "size = " << v.size() << endl;
    cout << "capacity = " << v.capacity() << endl << endl;

    vector<int> (v).swap(v);    //匿名对象
    cout << "size = " << v.size() << endl;
    cout << "capacity = " << v.capacity() << endl;

    getchar();
    return 0;
}

  执行结果

  重置大小后,容器中的元素只有3个,但是容量仍很大,浪费内存空间。

  采用匿名对象,调用拷贝构造函数用v初始化。

  然后匿名对象与v交换。此后容器v的元素和容量都为3,而匿名对象被析构。从而达到了收缩内存空间的目的。

发布了515 篇原创文章 · 获赞 135 · 访问量 30万+

猜你喜欢

转载自blog.csdn.net/liyazhen2011/article/details/103179974