码迷,mamicode.com
首页 > 其他好文 > 详细

vector的size和capacity改变时空间分配的过程

时间:2015-04-30 09:05:42      阅读:116      评论:0      收藏:0      [点我收藏+]

标签:

当增加新元素(s)时,如果超过当时的容量,则容量会扩充至两倍。如果两倍容量仍不足,就扩张至足够大的容量。

以一个例子来说明:

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

int main()
{
    int i;
    vector<int> iv(2,9);
    cout<<"size = "<<iv.size()<<endl;
    cout<<"capacity = "<<iv.capacity()<<endl;

    iv.push_back(1);
    cout<<"size = "<<iv.size()<<endl;
    cout<<"capacity = "<<iv.capacity()<<endl;

    iv.push_back(2);
    cout<<"size = "<<iv.size()<<endl;
    cout<<"capacity = "<<iv.capacity()<<endl;

    iv.push_back(3);
    cout<<"size = "<<iv.size()<<endl;
    cout<<"capacity = "<<iv.capacity()<<endl;

    iv.push_back(4);
    cout<<"size = "<<iv.size()<<endl;
    cout<<"capacity = "<<iv.capacity()<<endl;

    for(i = 0;i < iv.size();i++)
        cout<<iv[i]<<" ";
    cout<<endl;

    iv.push_back(5);
    cout<<"size = "<<iv.size()<<endl;
    cout<<"capacity = "<<iv.capacity()<<endl;
    for(i = 0;i < iv.size();i++)
        cout<<iv[i]<<" ";
    cout<<endl;

    iv.pop_back();
    iv.pop_back();
    cout<<"size = "<<iv.size()<<endl;
    cout<<"capacity = "<<iv.capacity()<<endl;

    iv.pop_back();
    cout<<"size = "<<iv.size()<<endl;
    cout<<"capacity = "<<iv.capacity()<<endl;

    vector<int>::iterator ivite = find(iv.begin(),iv.end(),1);
    if(ivite != iv.end())
        iv.erase(ivite);
    cout<<"size = "<<iv.size()<<endl;
    cout<<"capacity = "<<iv.capacity()<<endl;
    for(i = 0;i < iv.size();i++)
        cout<<iv[i]<<" ";
    cout<<endl;

    ivite = find(iv.begin(),iv.end(),2);
    if(ivite != iv.end())
        iv.insert(ivite,3,7);
    cout<<"size = "<<iv.size()<<endl;
    cout<<"capacity = "<<iv.capacity()<<endl;
    for(i = 0;i < iv.size();i++)
        cout<<iv[i]<<" ";
    cout<<endl;
    
    iv.clear();
    cout<<"size = "<<iv.size()<<endl;
    cout<<"capacity = "<<iv.capacity()<<endl;

    return 0;
}


vector的size和capacity改变时空间分配的过程

标签:

原文地址:http://blog.csdn.net/u011487593/article/details/45371091

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!