C++ List resize
C++ List resize function changes the size of the list container.
Following are the conditions:
If n is smaller than the current container size then the list container is reduced to n elements, removing all the elements that extends the n space.
If n is greater than the current container size then the size of the container is increased and more elements can be inserted in the expanded space.
Syntax
void resize(size_type n, value_type val )
Parameter
n : It is a new container size.
< val : It is a value which is to be inserted in a newly constructed space.
Return value
It does not return any value.
Example 1
Let's see a simple example when n is less than the current container size.
#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:
Content of list li :
1,2,3,4,5
Content of list li :
1,2,3
In this example, resize function decreases the size of the list container by 2. Therefore, the last two elements of the list has been removed and output becomes 1,2,3.
Example 2
Let's see a simple example when n is greater than the current container size.
#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:
Content of list li :
10,20,30,40
After resizing,Content of list li :
10,20,30,40,50,50,50
In this example, resize function increases the size of the list by 3 and the new element i.e 50 is inserted in a newly constructed space.