vector和unique_ptr及clear操作

该代码示例展示了C++中使用`unique_ptr`管理动态内存以及`vector`的操作,如添加元素、容量调整和清空容器。通过`push_back`与`move`来安全地向`vector`添加`unique_ptr`,并对比了不同清空`vector`的方法,包括`clear()`、`swap()`和`shrink_to_fit()`对容量的影响。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

int main()
{
    vector<unique_ptr<int>> demo;
    //demo.push_back(1);   编译错误

    unique_ptr<int> up(new int(1));
    //demo.emplace_back(up); //编译错误

    demo.push_back(std::move(up));

    cout << *demo[0] << endl;
    //cout << *up <<endl;  程序崩溃

    vector<int> v;
    v.push_back(1);
    v.push_back(2);
    v.push_back(3);
    v.push_back(4);
    v.push_back(5);
    

    cout << "size:" << v.size() << endl;  //5
    cout << "capacity:" << v.capacity() << endl;//6


    //清空方法1
    v.clear();
    cout << "after clear size:" << v.size() << endl;//0
    cout << "after clear capacity:" << v.capacity() << endl;//6

    //清空方法2
    vector<int>().swap(v);
    cout << "after swap size:" << v.size() << endl;//0
    cout << "after swap capacity:" << v.capacity() << endl; //0

    //清空方法3
    v.clear();
    v.shrink_to_fit();
    cout << "after swap size:" << v.size() << endl;//0
    cout << "after swap capacity:" << v.capacity() << endl;//0


    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值