vector uses reserve to reserve space

1. The difference between vector and ordinary array

  • Vector can be dynamically expanded and expanded
    dynamically: it is not to connect new space after the original space, but to find a larger space, and then copy the original data to the new space to release the original space

Initialize the vector directly. If there is a lot of data to be stored, it will be dynamically expanded multiple times, which affects efficiency. You can use reserve to reserve space.

2. Code

#include <iostream>
#include <sstream>
#include <iterator>
#include <vector>
#include <string>
#include <queue>

#include <fstream> // c++文件操作
#include <iomanip> // 设置输出格式

#include <numeric>
#include <algorithm>
#include <unordered_set>
#include "for_code.h"

#include <vector>

using namespace std;

int main(int argc, char const *argv[])
{
    
    
    vector<int> v1;
    vector<int> v2;

    //提前预留空间
    v1.reserve(1000); 

    int num1 = 0;
    int * vec_p1 = NULL;

    int num2 = 0;
    int * vec_p2 = NULL;

    for(int i=0;i<1000;i++)
    {
    
    
        v1.push_back(i);

        if (vec_p1 != &v1[0])
        {
    
    
            vec_p1 = &v1[0];
            num1++;
        }

        v2.push_back(i);

        if (vec_p2 != &v2[0])
        {
    
    
            vec_p2 = &v2[0];
            num2++;
        } 
    }

    cout << "num1:" << num1 << endl; //开辟的内存次数
    cout << "num2:" << num2 << endl; //开辟的内存次数

    return 0;
}

3. Results

Insert picture description here

Guess you like

Origin blog.csdn.net/qq_35632833/article/details/113481689
Recommended