命名空间
变体
操作

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

来自 cppreference.cn
 
 
 
 
void resize( size_type count );
(1) (自 C++11 起)
void resize( size_type count, const value_type& value );
(2) (自 C++11 起)

调整容器大小以容纳 count 个元素,如果 count == std::distance(begin(), end()) (即如果 count 等于当前大小) 则不执行任何操作。

如果当前大小大于 count,则容器将被缩减为其前 count 个元素。

如果当前大小小于 count,则

1) 将追加额外的 默认插入 元素。
2) 将追加 value 的额外副本。

内容

[编辑] 参数

count - 容器的新大小
value - 用于初始化新元素的值
类型要求
-
T 必须满足 DefaultInsertable 的要求才能使用重载 (1)。
-
T 必须满足 CopyInsertable 的要求才能使用重载 (2)。

[编辑] 复杂度

与当前大小和 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


[编辑] 参见

返回可能的最大元素数
(公共成员函数) [编辑]
检查容器是否为空
(公共成员函数) [编辑]