Vector reserve()

A vector is more efficient if you specify the vector's length before pushing values. You can do this with the reserve() method, which will guarantee that the vector can hold the number of elements reserved.

#include <iostream>
#include <vector>

using namespace std;

int main() {
    vector<int> myvector;
    int vector_size = 50;
    myvector.reserve(vector_size);

    for (int i = 0; i < vector_size; i++) {
        myvector.push_back(i);
    }

    return 0;
}

Last updated