vector中的resize与 reserve

void reserve (size_type n);

reserver函数用来给vector预分配存储区大小,即capacity的值 ,但是没有给这段内存进行初始化。reserve 的参数n是推荐预分配内存的大小,实际分配的可能等于或大于这个值,即n大于capacity的值,就会reallocate内存 capacity的值会大于或者等于n 。这样,当调用push_back函数使得size 超过原来的默认分配的capacity值时 避免了内存重分配开销。

需要注意的是:reserve 函数分配出来的内存空间,只是表示vector可以利用这部分内存,但vector不能有效地访问这些内存空间,访问的时候就会出现越界现象,导致程序崩溃。

void resize (size_type n);
void resize (size_type n, value_type val);

resize函数重新分配大小,改变容器的大小,并且创建对象

当n小于当前size()值时候,vector首先会减少size()值 保存前n个元素,然后将超出n的元素删除(remove and destroy)

当n大于当前size()值时候,vector会插入相应数量的元素 使得size()值达到n,并对这些元素进行初始化,如果调用上面的第二个resize函数,指定val,vector会用val来初始化这些新插入的元素

当n大于capacity()值的时候,会自动分配重新分配内存存储空间。

例子:

#include<algorithm>
#include<vector>
#include<list>
#include<iostream>
#include<string>
#include<numeric>
#include<iterator>
using namespace std;

int main()
{
    vector<double> v1={2,34,5,65,34,342,23,1,34};
    list<string> v2={"a","a","dfd","fd","a"};
    int count1=count(v1.begin(),v1.end(),34);
    cout<<count1<<endl;
    int count2=count(v2.begin(),v2.end(),"a");
    cout<<count2<<endl;
    cout<<accumulate(v1.begin(),v1.end(),0)<<endl;
    vector<int> vec; //此时vec为空
    //分配预留空间的插入
    vec.reserve(10);
    cout<<vec[0]<<endl;
    cout<<vec[9]<<endl;
    fill_n(vec.begin(),10,0);
    //没有分配预留空间的插入
    //fill_n(back_inserter(vec),10,0);
    return 0;
}

 

posted @ 2014-08-17 11:22  Jessica程序猿  阅读(6444)  评论(0编辑  收藏  举报