您的位置:首页 > 其它

vector容器成员函数resize与reserve的区别

2013-09-20 15:35 423 查看
resize是设置向量的大小:即向量的大小与容量相同。而reserve是设置向量的容量,并不改变向量的大小。另外:向量的最大大小是固定住,不可改变。例子:

#include
"stdafx.h"
#include
<iostream>
#include
<vector>
 
using namespace std;
 
typedefvector<int> VEC_INT;
int_tmain(int argc, _TCHAR* argv[])
{
    VEC_INTthevec;
    cout<<"before insert data:"<<endl;
    cout<<"the size of vector:"<<thevec.size()<<endl;
    cout<<"the capasity of vector:"<<thevec.capacity()<<endl;
    cout<<"the max size of vector:"<<thevec.max_size()<<endl;
    cout<<"after insert data:"<<endl;
    thevec.push_back(42);
    cout<<"the size of vector:"<<thevec.size()<<endl;
    cout<<"the capasity of vector:"<<thevec.capacity()<<endl;
    cout<<"the max size of vector:"<<thevec.max_size()<<endl;
 
    thevec.reserve(100);
    cout<<"After reserve (100):"<<endl;
    cout<<"the size of vector:"<<thevec.size()<<endl;
    cout<<"the capasity of vector:"<<thevec.capacity()<<endl;
    cout<<"the max size of vector:"<<thevec.max_size()<<endl;
 
    thevec.resize(1000);
    cout<<"After resize (1000):"<<endl;
    cout<<"the size of vector:"<<thevec.size()<<endl;
    cout<<"the capasity of vector:"<<thevec.capacity()<<endl;
    cout<<"the max size of vector:"<<thevec.max_size()<<endl;
    return 0;
}

运行结果:



可以看出:默认情况下,向量的大小和容量是相同的,如果用resize改变向量的大小,则同时改变了向量的容量。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: