【动手出真知】vector reverse & resize

本文详细介绍了C++中vector的resize和reserve方法,对比了它们对size和capacity的影响,重点强调了resize会改变大小并可能触发容量扩展,而reserve则只预分配空间但不会改变当前元素数量。

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

  • reverse vs resize
  • reserve: size-内容不变,指定的reserve参数 > size 变化,<size 不变
  • resize: 截掉/扩充vector,if(resize参数 < capacity)capacity不变,else{ vector扩容,capacity肯定改变}
  • capacity vs size
    要分清哦
#include <string>
#include <iostream>
#include <vector>

using namespace std;

int main()
{
    std::cout << "\n=======测试resize===\n" << endl;

    vector<int> v1{1, 2, 3, 4, 5};
    std::cout << "v1 source data is : " << "\n";
    for (auto& v : v1)
    {
        std::cout << v << " ";
    }
    std::cout << "\n" << " v1.size=" << v1.size() << " v1.capacity=" << v1.capacity() << endl;

    std::cout << "after resize to 2" << endl;
    v1.resize(2); //尺寸由5改变为2,多余字符被截掉了,只剩下1 2 
    for (auto& v : v1)
    {
        std::cout << v << " ";
    }
    std::cout << " v1.size=" << v1.size() << " v1.capacity=" << v1.capacity() << endl;

    std::cout << "after resize to 12" << endl;
    v1.resize(12, 10000); //尺寸由2改变为12,填充10000
    for (auto& v : v1)
    {
        std::cout << v << ", ";
    }
    std::cout << "\n" << " v1.size=" << v1.size() << " v1.capacity=" << v1.capacity() << endl;
    v1.push_back(88);
    std::cout << "\n" << "v1扩容, v1.size=" << v1.size() << " v1.capacity=" << v1.capacity() << endl;



    std::cout << "\n=======测试reverse===\n" << endl;

    vector<int> v2{1, 2, 3, 4, 5};
    std::cout << "v2 source data is : " << "\n";
    for (auto& v : v2)
    {
        std::cout << v << ", ";
    }
    std::cout << "\n" << " v2.size=" << v2.size() << " v2.capacity=" << v2.capacity() << endl;

    std::cout << "after reserve to 2" << endl;
    v2.reserve(2); // size-内容不变,指定的reserve参数 > size 变化,<size 不变
    for (auto& v : v2)
    {
        std::cout << v << ", ";
    }
    std::cout << "\n" << " v2.size=" << v2.size() << " v2.capacity=" << v2.capacity() << endl;
    //std::cout << "after resize to 12" << endl;
    //v2.resize(12, 0);
    //std::cout << "\n" << " v2.size=" << v2.size() << " v2.capacity=" << v2.capacity() << endl;

    std::cout << "\nafter reserve to 12" << endl;
   
    v2.reserve(12); //size-内容不变,指定的reserve参数 > size 变化,<size 不变
    for (auto& v : v2)
    {
        std::cout << v << ", ";
    }
    std::cout << "\n" << " v2.size=" << v2.size() << " v2.capacity=" << v2.capacity() << endl;

    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值