zoukankan      html  css  js  c++  java
  • 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
    */ 
  • 相关阅读:
    Activiti6-IdentityService(学习笔记)
    Activiti6-TaskService(学习笔记)重要
    选定用户与用户组启动流程(学习笔记)
    Activiti6作业执行器Job Executor配置(学习笔记)
    命令模式与责任链模式以及命令拦截器的配置(学习笔记)
    Activiti6事件及监听器配置(学习笔记)
    基于MySQL的Activiti6引擎创建
    abowman
    wpf 遍历listview 时 传入指定类型 得到指定类型控件info
    wpf listview 行变色
  • 原文地址:https://www.cnblogs.com/laohaozi/p/12538030.html
Copyright © 2011-2022 走看看