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.
- If the list already has more than n elements, then the function erases the elements from the list except the first n element.
- If the list contains less than n elements, then the function adds the difference number of elements to the list with their default values.
- The function also accepts a parameter val, if this parameter is specified and the number of elements in the list container is less than n then the function adds elements to the list with their value assigned to val.
Syntax:
list_name.resize(int n, value_type val)
Parameters: This function accepts two parameters as described below.
- n : This parameter specifies the number of elements upto which the list is needed to be resized.
- val: This is an optional parameter and if it is specified and the list contains less than n elements then the function will add elements to the list with their value assigned to val.
Return Value: This function does not return any value. Below program illustrate the list::resize() function in C++ STL:
CPP
#include <bits/stdc++.h>
using namespace std;
int main()
{
list< int > demoList;
demoList.push_back(10);
demoList.push_back(20);
demoList.push_back(30);
demoList.push_back(40);
cout << "Initial List: ";
for ( auto itr = demoList.begin(); itr != demoList.end(); itr++)
cout << *itr << " ";
demoList.resize(2);
cout << "\n\nList after first resize: ";
for ( auto itr = demoList.begin(); itr != demoList.end(); itr++)
cout << *itr << " ";
demoList.resize(4);
cout << "\n\nList after second resize: ";
for ( auto itr = demoList.begin(); itr != demoList.end(); itr++)
cout << *itr << " ";
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)
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!
Last Updated :
14 Jun, 2022
Like Article
Save Article