vector reserve() in C++

reserve(): It attempts to preallocate enough memory for the specified number of elements. 

Parameters: 

n: Number of elements required. 

File: vector.tcc

Syntax:

vecName.reserve(n)

For Example:

vector<int> vec

vec.reserve(5) => It allocate size of 5.

Approach

C++

#include <bits/stdc++.h>
using namespace std;

int main()
{
    vector<int> vec;

    vec.reserve(5);
    for (int i = 1; i <= 5; i++)
    {
        vec[i - 1] = i;
    }
    for (int i = 0; i < 5; i++)
        cout << vec[i] << " ";
    
    return 0;
}


No comments:

Post a Comment