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.

另見