vector-reserve

vector-reserve//////////////////////…

大家好,欢迎来到IT知识分享网。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 */ 

免责声明:本站所有文章内容,图片,视频等均是来源于用户投稿和互联网及文摘转载整编而成,不代表本站观点,不承担相关法律责任。其著作权各归其原作者或其出版社所有。如发现本站有涉嫌抄袭侵权/违法违规的内容,侵犯到您的权益,请在线联系站长,一经查实,本站将立刻删除。 本文来自网络,若有侵权,请联系删除,如若转载,请注明出处:https://yundeesoft.com/34693.html

(0)

相关推荐

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注

关注微信