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<intvec;

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


No comments:

Post a Comment