std::forward_list resize() 方法
- 自 C++11 起
// (1) Non const version only
void resize( size_type count );
// (2) Non const version only
void resize( size_type count, const value_type& value );
将容器的大小调整为包含 count
个元素。
如果当前大小大于 count
,则容器将被缩减为其前 count
个元素。
如果当前大小小于 count
- (1) 追加默认构造的元素。
- (2) 追加
value
的副本。
参数
count
- 容器的新大小value
- 用于初始化新元素的值
类型要求
- (1) -
T
(容器的元素类型) 必须满足DefaultInsertable
的要求。 - (2) -
T
(容器的元素类型) 必须满足CopyInsertable
的要求。
返回值
(无)
复杂度
与当前大小和 count
之间的差值成线性关系 - **O(size() - count)**。
重要
由于需要遍历列表以到达要擦除的第一个元素/要插入的结束位置,可能会有额外的复杂性。
异常
(无)
备注
如果重载(1)中的值初始化是不期望的,例如,如果元素是非类类型且不需要清零,则可以通过提供自定义的 Allocator::construct()
来避免。
示例
Main.cpp
#include <iostream>
#include <forward_list>
int main()
{
std::forward_list<int> c = {1, 2, 3};
std::cout << "The forward_list holds: ";
for (const auto& el: c) std::cout << el << ' ';
std::cout << '\n';
c.resize(5);
std::cout << "After resize up to 5: ";
for (const auto& el: c) std::cout << el << ' ';
std::cout << '\n';
c.resize(2);
std::cout << "After resize down to 2: ";
for (const auto& el: c) std::cout << el << ' ';
std::cout << '\n';
c.resize(6, 4);
std::cout << "After resize up to 6 (initializer = 4): ";
for (const auto& el: c) std::cout << el << ' ';
std::cout << '\n';
}
输出
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