7.vector预留空间

2021-04-10  本文已影响0人  lxr_
#include<iostream>
using namespace std;

#include<vector>
//减少vector在动态扩展容量时的开辟内存的次数
//reserve(int len) //容器预留len个元素长度,预留位置不初始化,元素不可访问

void test0701()
{
    vector<int> v;

    //利用reserve预留空间
    v.reserve(100000);

    int num = 0;//统计开辟内存次数
    int* p = NULL;

    for (int i = 0; i < 100000; i++)
    {
        v.push_back(i);

        if (p != &v[0])
        {
            p = &v[0];
            num++;
            cout << v.capacity() << endl;
        }
    }
    cout << "num=" << num << endl;
    
}

int main()
{

    test0701();

    system("pause");
    return 0;
}
上一篇 下一篇

猜你喜欢

热点阅读