vector中的reserve() 与 resize()

36 篇文章 2 订阅
18 篇文章 0 订阅

resize()与reserve()都是vector容器中的方法:

resize():改变了capacity()size()

reserve():增加了vector的capacity(),但是它的size()没有改变

#include <iostream>
#include <stdio.h>
#include <vector>
#include<functional>
using namespace std;

int main(int argc, char* argv[])
{
    vector<int> v;
    vector<int>::iterator it;
    vector<int> v2;

    v.push_back(1);
    v.push_back(2);
    v.push_back(3);
    v.push_back(4);
    v.push_back(11);
    v.push_back(12);
    v.push_back(13);
    v.push_back(14);

    v2.push_back(21);
    v2.push_back(22);
    v2.push_back(23);
    v2.push_back(24);
    v2.push_back(25);
    v2.push_back(26);
    v2.push_back(27);
    v2.push_back(28);

    cout << "original data v:" << "===========start============" << "\n";
    for (it = v.begin(); it != v.end(); ++it) {
        cout << *it << endl;
    }
    cout << "original data v:" << "============end===========" << "\n";

    cout << "original data v:" << ": capacity()=" << v.capacity() << ", size()=" << v.size() << "\n";

    v.resize(10); //改变capacity()和size()

    cout << "after resize data" << ": capacity()=" << v.capacity() << ", size()=" << v.size() << "\n";
    for (it = v.begin(); it != v.end(); ++it) {
        cout << *it << endl;
    }

    cout << "original data v2:" << "===========start============" << "\n";
    for (it = v2.begin(); it != v2.end(); ++it) {
        cout << *it << endl;
    }
    cout << "original data v2:" << "============end===========" << "\n";

    cout << "original data v2:" << ": capacity()=" << v2.capacity() << ", size()=" << v2.size() << "\n";

    v2.reserve(10);  //只增加了capacity()
    cout << "after reserve data" << ": capacity()=" << v2.capacity() << ", size()=" << v2.size() << "\n";

    return 0;
}

根据上面的打印可以看出:

vector.resize():改变了capacity()size()

vector.reserve():增加了vector的capacity(),但是它的size()没有改变

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值