std::vector<T,Allocator>::resize
来自 cppreference.cn
void resize( size_type count ); |
(1) | (constexpr since C++20) |
void resize( size_type count, const value_type& value ); |
(2) | (constexpr since C++20) |
调整容器大小以容纳 count 元素,如果 count == size() 则不执行任何操作。
如果当前大小大于 count,则容器将缩减为其前 count 个元素。
如果当前大小小于 count,则
1) 追加额外的 默认插入 元素。
2) 追加 value 的额外副本。
Contents |
[edit] Parameters
count | - | 容器的新大小 |
value | - | 用于初始化新元素的值 |
Type requirements | ||
-T must meet the requirements of MoveInsertable and DefaultInsertable in order to use overload (1). | ||
-T must meet the requirements of CopyInsertable in order to use overload (2). |
[edit] Complexity
与当前大小和 count 之间的差值呈线性关系。如果容量小于 count,则可能由于重新分配而增加复杂度。
Exceptions
如果由于任何原因抛出异常,这些函数都不会产生影响(强异常安全保证)。虽然未明确指定,但如果新 vector
所需的容量超过 max_size(),则会抛出 std::length_error。
在重载 (1) 中,如果 |
(since C++11) |
Notes
如果在重载 (1) 中的值初始化是不 желаしい 的,例如,如果元素是非类类型且不需要归零,则可以通过提供 自定义 Allocator::construct
来避免。
当调整为较小尺寸时,Vector 容量永远不会减少,因为这会使所有迭代器失效,而规范仅使指向/在擦除元素之后的迭代器失效。
[edit] Example
Run this code
#include <vector> #include <iostream> void print(auto rem, const std::vector<int>& c) { for (std::cout << rem; const int el : c) std::cout << el << ' '; std::cout << '\n'; } int main() { std::vector<int> c = {1, 2, 3}; print("The vector 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); }
Output
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
Defect reports
The following behavior-changing defect reports were applied retroactively to previously published C++ standards.
DR | Applied to | Behavior as published | Correct behavior |
---|---|---|---|
LWG 679 | C++98 | resize() passed value by value |
passes by const reference |
LWG 1525 | C++98 | the behavior of resize(size()) was not specified | specified |
LWG 2033 | C++11 | 1. elements were removed by using erase()[1] 2. the type requirements of T were incorrect |
1. uses pop_back() 2. corrected |
LWG 2066 | C++11 | overload (1) did not have the exception safety guarantee of overload (2) |
added |
LWG 2160 | C++11 | elements were removed by using pop_back()[2] due to the resolution of LWG 2033 |
does not specify the method of removing elements |
- ↑ erase() can remove elements in the middle of a
vector
, so the value type is required to be MoveAssignable so that the elements following the removed section can be moved forward to fill the gap. However,resize()
can only remove elements at the end of thevector
, making the MoveAssignable unnecessary. - ↑ Removing elements by using pop_back() implies that the elements are required to be removed from back to front.
[edit] See also
返回最大可能的元素数量 (public member function) | |
返回元素数量 (public member function) | |
返回当前已分配存储中可以容纳的元素数量 (public member function) | |
检查容器是否为空 (public member function) |