Namespaces
Variants

std::forward_list<T,Allocator>:: resize

From cppreference.net

void resize ( size_type count ) ;
(1) (自 C++11 起)
(自 C++26 起为 constexpr)
void resize ( size_type count, const value_type & value ) ;
(2) (自 C++11 起)
(自 C++26 起为 constexpr)

将容器大小调整为包含 count 个元素:

  • count 等于当前尺寸,则不执行任何操作。
  • 若当前尺寸大于 count ,容器将缩减至其前 count 个元素。
  • 若当前尺寸小于 count ,则:
1) 附加的 default-inserted 元素将被追加。
2) 额外的 value 副本会被追加。

目录

参数

count - 容器的新大小
value - 用于初始化新元素的值
类型要求
-
若满足下列条件,则行为未定义:
1) T 不满足 DefaultInsertable forward_list 的要求。
2) T 不满足 CopyInsertable forward_list 的要求。

复杂度

与当前大小和 count 之间的差值呈线性关系。由于需要遍历列表以定位首个待擦除元素/插入的终止位置,可能存在额外复杂度。

注释

如果在重载 ( 1 ) 中的值初始化不可取,例如当元素为非类类型且不需要清零时,可以通过提供 自定义的 Allocator::construct 来避免这种情况。

示例

#include <forward_list>
#include <iostream>
void print(auto rem, const std::forward_list<int>& c)
{
    for (std::cout << rem; const int el : c)
        std::cout << el << ' ';
    std::cout << '\n';
}
int main()
{
    std::forward_list<int> c = {1, 2, 3};
    print("The forward_list holds: ", c);
    c.resize(5);
    print("After resize up to 5: ", c);
    c.resize(2);
    print("After resize down to 2: ", c);
    c.resize(6, 4);
    print("After resize up to 6 (initializer = 4): ", c);
}

输出:

The forward_list holds: 1 2 3
After resize up to 5: 1 2 3 0 0
After resize down to 2: 1 2
After resize up to 6 (initializer = 4): 1 2 4 4 4 4


参见

返回可能容纳的最大元素数
(公开成员函数)
检查容器是否为空
(公开成员函数)