Open In App

list resize() function in C++ STL

The list::resize() is a built-in function in C++ STL which is used to resize a list container. It takes a number n as parameter and resizes the list container to contain exactly n elements.

Syntax:



list_name.resize(int n, value_type val)

Parameters: This function accepts two parameters as described below.

Return Value: This function does not return any value. Below program illustrate the list::resize() function in C++ STL: 






// CPP program to illustrate the
// list::resize() function
#include <bits/stdc++.h>
using namespace std;
 
int main()
{
    // Creating a list
    list<int> demoList;
 
    // Adding elements to the list
    demoList.push_back(10);
    demoList.push_back(20);
    demoList.push_back(30);
    demoList.push_back(40);
 
    // Initial list:
    cout << "Initial List: ";
    for (auto itr = demoList.begin(); itr != demoList.end(); itr++)
        cout << *itr << " ";
 
    // Resize list to contain less elements
    demoList.resize(2);
    cout << "\n\nList after first resize: ";
    for (auto itr = demoList.begin(); itr != demoList.end(); itr++)
        cout << *itr << " ";
 
    // Resize list to contain more elements
    demoList.resize(4);
    cout << "\n\nList after second resize: ";
    for (auto itr = demoList.begin(); itr != demoList.end(); itr++)
        cout << *itr << " ";
 
    // resize list to contain more elements
    // with a specified value
    demoList.resize(5, 50);
    cout << "\n\nList after third resize: ";
    for (auto itr = demoList.begin(); itr != demoList.end(); itr++)
        cout << *itr << " ";
 
    return 0;
}

Output:
Initial List: 10 20 30 40 

List after first resize: 10 20 

List after second resize: 10 20 0 0 

List after third resize: 10 20 0 0 50

Time Complexity – Linear O(N)


Article Tags :
C++