std::vector resize() 方法
- 自 C++20 起
- 自 C++11 起
- 直到 C++11
// prism-push-types:size_type,value_type
// (1) Non const version only
constexpr void resize( size_type count );
// (2) Non const version only
constexpr void resize( size_type count, value_type const& value );
// prism-push-types:size_type,value_type
// (1) Non const version only
void resize( size_type count );
// (2) Non const version only
void resize( size_type count, value_type const& value );
// prism-push-types:size_type
// (2) Non const version only
void resize( size_type count, T value = T() );
将容器大小调整为包含 count
个元素。如果当前大小大于 count
,容器将缩减为前 count
个元素。
如果当前大小小于 count
,
- (1) 会追加额外的默认插入元素。
- (2) 会追加值的额外副本。
参数
count
- 容器的新大小value
- 用于初始化新元素的值
类型要求
此列表中的 T
是容器的元素类型。
- (1) -
T
必须满足MoveInsertable
和DefaultInsertable
的要求。 - (2) -
T
必须满足CopyInsertable
的要求。
返回值
(无)
复杂度
复杂度为 size()
和 count
之间差值的线性关系 - O(size() - count)。
重要
如果 capacity()
小于 count
,则可能由于重新分配而增加额外的复杂度。
异常
如果抛出异常,此函数不产生任何效果(强异常保证)。
- 自 C++11 起
在重载 (1) 中,如果
T
的移动构造函数不是 noexcept 且 T
无法 CopyInsertable 到 *this
中,则 vector 将使用会抛出异常的移动构造函数。如果它抛出异常,则保证失效且效果未指定。备注
如果重载 (1) 中的值初始化不合需要,例如,如果元素是非类类型且不需要清零,
可以通过提供自定义的 Allocator::construct()
来避免。当调整大小到更小的时候,vector 的容量永远不会减少,因为那会使所有迭代器失效,而不仅仅是会因等效的 pop_back()
调用序列而失效的迭代器。
示例
Main.cpp
#include <iostream>
#include <vector>
int main()
{
std::vector<int> c = {1, 2, 3};
std::cout << "The vector 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 vector 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