# List resize() function in C++ STL

C++Server Side ProgrammingProgramming

In this article we will be discussing the working, syntax and examples of list::resize() function in C++.

## What is a List in STL

List is a data structure that allows constant time insertion and deletion anywhere in sequence. Lists are implemented as doubly linked lists. Lists allow non-contiguous memory allocation. List perform better insertion extraction and moving of element in any position in container than array, vector and deque. In List the direct access to the element is slow and list is similar to forward_list, but forward list objects are single linked lists and they can only be iterated forwards.

## What is list::resize()?

list::resize() is an inbuilt function in C++ STL which is declared in header file. resize() is used to resize the list container. It resizes the container, so that it will contain the number of elements which we give in the argument of the function.

### Syntax

list_name.resize(int n);

or

list_name.resize(int n, const value_type &val);

This function can accept either one or two parameters within.

### Parameters

• n − It is an integer type which defines new container size (number of elements).

• val − The object whose content is to be copied to all the spaces in the container.

### Return value

This function returns nothing. It will only resize the container.

## Example

Live Demo

#include <bits/stdc++.h>
using namespace std;
int main(){
//create a list
list<int> myList;
//insert elements to the list
myList.push_back(1);
myList.push_back(2);
myList.push_back(3);
myList.push_back(4);
//elemets in th list before Resize
cout << "List elements are : ";
for (auto i = myList.begin(); i!= myList.end(); i++)
cout << *i << " ";
//Resizing list
myList.resize(5);
cout<<"\nList after resize: ";
for (auto i = myList.begin(); i!= myList.end(); i++)
cout << *i << " ";
//Resizing list again
myList.resize(6);
cout<<"\nList after resizing it again : ";
for (auto i = myList.begin(); i != myList.end(); i++)
cout << *i << " ";
return 0;
}

## Output

If we run the above code then it will generate the following output

List elements are : 1 2 3 4
List after resize : 1 2 3 4 0
List after resizing it again : 1 2 3 4 0 0
Published on 26-Feb-2020 11:53:03