命名空间
变体
操作

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

来自 cppreference.cn
< cpp‎ | 容器‎ | forward_list
 
 
 
 
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 - 用于初始化新元素的值
类型要求
-
为了使用重载 (1),T 必须满足 DefaultInsertable 的要求。
-
为了使用重载 (2),T 必须满足 CopyInsertable 的要求。

[编辑] 复杂度

时间复杂度为当前大小与 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


[编辑] 另请参阅

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