List Resize Function - C++ Programming Tutorial
C++ Course / Dynamic Programming / List Resize Function

List Resize Function

BLUF: Mastering List Resize Function is a critical step in becoming a proficient C++ developer. This lesson provides a deep dive into the syntax, performance considerations, and real-world applications of this concept.
Key Performance Insight: List Resize Function

C++ is renowned for its efficiency. Learn how List Resize Function enables low-level control and high-performance computing in the tutorial below.

C++ List resize

The resize function in C++ alters the size of the list container.

Following are the conditions:

If the value of n is less than the current size of the container, the list container will be resized to contain only n elements, effectively eliminating any elements beyond the new size limit.

If the value of n exceeds the current size of the container, the container's capacity is enlarged to accommodate additional elements within the expanded area.

Syntax

Example

void resize(size_type n, value_type val )

Parameter

n : It is a new container size.

< val : It represents a data value that needs to be added to a freshly created location.

Return value

It does not return any value.

Example 1

Let's consider a basic scenario where n is smaller than the current size of the container.

Example

#include <iostream>
#include<list>
using namespace std;
int main()
{
  list<int> li={1,2,3,4,5};
  list<int>::iterator itr;
  std::cout << "Content of list li :" << std::endl;
  for(itr=li.begin();itr!=li.end();++itr)
  cout<<*itr<<",";
  li.resize(3);
  cout<<'\n';
  std::cout << "After resizing,Content of list li :" << std::endl;
  for(itr=li.begin();itr!=li.end();++itr)
   cout<<*itr<<",";
    return 0;
}

Output:

Output

Content of list li :
1,2,3,4,5
Content of list li :
1,2,3

In this instance, the resize method reduces the size of the list container by 2 elements. As a result, the final two elements in the list are eliminated, and the resulting output is 1, 2, 3.

Example 2

Let's consider a basic scenario where n exceeds the current size of the container.

Example

#include <iostream>
#include<list>
using namespace std;
int main()
{
  list<int> li={10,20,30,40};
  list<int>::iterator itr;
  std::cout << "Content of list li :" << std::endl;
  for(itr=li.begin();itr!=li.end();++itr)
  cout<<*itr<<",";
  li.resize(7,50);
  cout<<'\n';
  std::cout << "After resizing,Content of list li :" << std::endl;
  for(itr=li.begin();itr!=li.end();++itr)
   cout<<*itr<<",";
    return 0;
}

Output:

Output

Content of list li :
10,20,30,40
After resizing,Content of list li :
10,20,30,40,50,50,50

In this instance, the resize method augments the list's size by 3, accommodating the addition of a new element, specifically 50, in a freshly created memory space.

Input Required

This code uses input(). Please provide values below:

Logic Practice
Install Logic Practice
Add to home screen for a faster app-like experience