• 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;
    }
  • 相关阅读:
    Linux 模块管理
    python 调试方法
    LFS(Linux From Scratch)学习
    Vim完全教程
    OpenSSL基础知识
    关于jiffies回绕以及time_after,time_before
    十分简便的APK反编译(Mac 版本号 具体解释)
    亚马逊是怎样颠覆商业软件高昂价格这座”柏林墙”的
    Android自己定义控件
    Android基础新手教程——4.1.1 Activity初学乍练
  • 原文地址:https://www.cnblogs.com/wuchanming/p/3917552.html
Copyright © 2020-2023  润新知