清空string 容器与vector容器(转载)

说明
在STL中 vector和string 是比较特殊的,clear()之后是不会释放内存空间的,也就是size()会清零,但capacity()不会改变,需要手动去释放,说明 clear() 没有释放内存。
想释放空间的话,除了swap一个空string外,c++11里新加入的的std::basic_string::shrink_to_fit 也可以。

代码
注意string的swap清空方法为:string().swap(str);

vector的swap清空方法为:nums.swap(vector<int>());

#include <iostream>
#include <string>
 
int main()
{
    std::string s;
    std::cout << "Default-constructed capacity is " << s.capacity()
        << " and size is " << s.size() << '\n';
    for (int i = 0; i < 42; i++)
        s.append(" 42 ");
    std::cout << "Capacity after a couple of appends is " << s.capacity()
        << " and size is " << s.size() << '\n';
    s.clear();
    std::cout << "Capacity after clear() is " << s.capacity()
        << " and size is " << s.size() << '\n';
    s.shrink_to_fit();
    std::cout << "Capacity after shrink_to_fit() is " << s.capacity()
        << " and size is " << s.size() << '\n';
    for (int i = 0; i < 42; i++)
        s.append(" 42 ");
    std::cout << "Capacity after a couple of appends is " << s.capacity()
        << " and size is " << s.size() << '\n';
    string().swap(s);
    std::cout << "Capacity after swap() is " << s.capacity()
        << " and size is " << s.size() << '\n';
}


输出为:

Default-constructed capacity is 15 and size is 0
Capacity after a couple of appends is 235 and size is 168
Capacity after clear() is 235 and size is 0
Capacity after shrink_to_fit() is 15 and size is 0
Capacity after a couple of appends is 235 and size is 168
Capacity after swap() is 15 and size is 0
 
————————————————

                            版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
                        
原文链接:https://blog.csdn.net/qq_41687938/article/details/117731243

C++ string清空并释放内存空间的两种方法(shrink_to_fit()、swap())_c++ string 释放-CSDN博客

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值