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.

参数

n
New container size, expressed in number of elements.
成员类型size_type是一种无符号整型类型。
val
Object whose content is copied to the added elements in case that n is greater than the current container size.
成员类型value_typeis the type of the elements in the container, defined in forward_list as an alias of the first template parameter (T).

返回值



In case of growth, the storage for the new elements is allocated usingallocator_traits<allocator_type>::construct()分配,这在失败时可能会抛出异常(对于默认的 allocatorbad_alloc如果分配请求不成功,则抛出)。

示例

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


复杂度

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

迭代器有效性

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

数据竞争

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

异常安全

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.

另见