public member function
<forward_list>

std::forward_list::resize

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

If n is smaller than the current number of elements in the container, the content is trimmed to contain only its first n elements, removing those beyonf (and destroying them).

If n is greater than the current number of elements in the container, the content is expanded by inserting at the end as many elements as needed to reach a size of n elements. If val is specified, the new elements are initialized as copies of val, otherwise, they are value-initialized.

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

Parameters

n
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 n 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 << '\n';

  return 0;
}


mylist contains: 10 20 30 100 100

Complexity

Linear in the number number of elements inserted/erased (constructor/destructor), plus up to linear in the size (iterator advance).

Iterator validity

Iterators, pointers and references referring to elements removed by the function are invalidated.
All other iterators, pointers and references keep their validity.

Data races

The container is modified.
Removed elements are modified. Concurrently accessing or modifying other elements is safe.

Exception safety

If the operation decreases the size of the container, the function never throws exceptions (no-throw guarantee).
Otherwise, if an exception is thrown, the container is left with a valid state (basic guarantee): Constructing elements or allocating storage may throw.

See also