public member function

std::forward_list::resize

<forward_list>
void resize ( size_type sz );
void resize ( size_type sz , const value_type& val );
Change size
Resizes the container to contain sz elements.

If sz is smaller than the current number of elements in the container, the content is trimmed to contain only its first sz elements, the rest being dropped (and their destructor being called).

If sz is greater than the current number fo elements in the container, the content is expanded by inserting at the end as many elements as needed to reach a size of sz elements. With the first version, the elements are default-initialized, while with the second they are copy-initialized as a copy of val.

Notice that this function changes the actual content of the container by inserting or erasing elements from it.

Parameters

sz
New container size, expressed in number of elements.
Member type size_type is an unsigned integral type.
val
Object whose content is copied to the added elements in case that sz is greater than the current container size.
Member type value_type is the type of the elements in the container, defined in forward_list as an alias of the first template parameter (T).

Return Value

none

In case of growth, the storage for the new elements is allocated using allocator_traits<allocator_type>::construct(), which may throw exceptions on failure (for the default allocator, bad_alloc is thrown if the allocation request does not succeed).

Example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
// resizing forward_list
#include <iostream>
#include <forward_list>

int main ()
{
  std::forward_list<int> mylist = {10, 20, 30, 40, 50};
                                // 10 20 30 40 50
  mylist.resize(3);             // 10 20 30
  mylist.resize(5,100);         // 10 20 30 100 100

  std::cout << "mylist contains:";
  for (int& x: mylist) std::cout << " " << x;
  std::cout << std::endl;

  return 0;
}


mylist contains: 10 20 30 100 100

Complexity

If the container grows, linear in the number number of elements inserted (constructor), plus up to linear on the new size (iterator advance)
If the container shrinks, linear on the number of elements erased (destructions), plus up to linear on the new size (iterator advance).

Iterator validity

All the iterators, pointers and references to elements that have not been removed remain valid after the resize and refer to the same elements they were referring to before.

See also