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

来自cppreference.com
 
 
 
 
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) 追加额外的默认插入的元素。
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("forward_list 持有:", c);
 
    c.resize(5);
    print("在增加大小到 5 之后:", c);
 
    c.resize(2);
    print("在减少大小到 2 之后:", c);
 
    c.resize(6, 4);
    print("在增加大小到 6 之后(初始化器 = 4):", c);
}

输出:

forward_list 持有:1 2 3
在增加大小到 5 之后:1 2 3 0 0
在减少大小到 2 之后:1 2
在增加大小到 6 之后(初始化器 = 4):1 2 4 4 4 4


[编辑] 参阅

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