• vector-reserve


    ////////////////////////////////////////
    //      2018/04/18 12:13:12
    //      vector-reserve
    
    /*
        size是当前vector容器真实占用的大小,也就是容器当前拥有多少个容器。
        capacity是指在发生realloc前能允许的最大元素数,即预分配的内存空间。
        当然,这两个属性分别对应两个方法:resize()和reserve()。
        使用resize(),容器内的对象内存空间是真正存在的。
        使用reserve()仅仅只是修改了capacity的值,容器内的对象并没有真实的内存空间(空间是"野"的)。
        此时切记使用[]操作符访问容器内的对象,很可能出现数组越界的问题。
    */
    #include <iostream>
    #include <vector>
    
    using namespace std;
    
    int main(){
    
        vector<int> v(5, 0);  // 5 elements each-value 0
        /*- - - - - - - - - - - - */
        cout << "Size of v = " << v.size() << endl;
        cout << "Capacity v = " << v.capacity() << endl;
        cout << "Value of each elements is ";
        for (int i = 0; i < v.size(); i++){
            cout << v[i] << " ";
        }
        cout << endl;
    
        v[0] = 5;       // new value for first element
        v[1] = 8;
        v.push_back(3);  // creates new (6th) elements of vector
        v.push_back(7);  // automatically increases size
        cout << endl;    // capacity of vector v
        cout << "Size of v = " << v.size() << endl;
        cout << "Capacity v = " << v.capacity() << endl;
        cout << "Value of each elements is ";
        for (int i = 0; i < v.size(); i++){
            cout << v[i] << " ";
        }
        cout << endl;
        v.reserve(100);     // increase capacity to 100
        cout << "Size of v1_int = " << v.size() << endl;
        cout << "Capacity v1_int = " << v.capacity() << endl;
    
        int size = sizeof(v); // how big is vector itself
        cout << "sizeof v =" << size << endl;
    
        return 0;
    }
    
    /*
    OUTPUT:
        Size of v = 5
        Capacity v = 5
        Value of each elements is 0 0 0 0 0
    
        Size of v = 7
        Capacity v = 7
        Value of each elements is 5 8 0 0 0 3 7
        Size of v1_int = 7
        Capacity v1_int = 100
        sizeof v =16
    */ 
  • 相关阅读:
    maven pom
    Amazon(vpc)对等网络
    AWS IAM用户启用MFA
    AWS系列-EC2实例镜像选择
    AWS系列-EC2实例添加磁盘
    AWS系列-AWS EC2实例类型改配(机器配置升级)
    AWS必要了解知识
    AWS系列-EC2默认限制说明
    AWS系列-S3实现文件服务页面展示
    AWS 区域与可用区
  • 原文地址:https://www.cnblogs.com/laohaozi/p/12538030.html
Copyright © 2020-2023  润新知