在线文档教程
C++
容器 | Containers

std::vector::resize

向量::调整大小

void resize( size_type count, T value = T() (until C++11)
void resize( size_type count (1)(since C++11)
void resize( size_type count, const value_type& value (2)(since C++11)

调整容器的大小以包含count元素。

如果当前大小大于count,容器被简化为第一个容器。count元素。

If the current size is less than count, additional elements are appended and initialized with copies of value.(until C++11)
If the current size is less than count, 1) additional default-inserted elements are appended 2) additional copies of value are appended(since C++11)

参数

count-new size of the container
value-the value to initialize the new elements with

类型要求

-T必须满足MoveInsertable和DefaultInsertable的要求,才能使用过载%281%29。

T必须满足CopyInsertable的要求才能使用过载%282%29。

返回值

%280%29

复杂性

当前大小与count...

例外

如果引发异常,则此函数不会影响%28强例外保证29%。

In overload (1), if T's move constructor is not noexcept and T is not CopyInsertable into *this, vector will use the throwing move constructor. If it throws, the guarantee is waived and the effects are unspecified.(since C++11)

注记

如果重载%281%29中的值初始化是不可取的,例如,如果不需要非类类型的元素,并且不需要零输出,则可以通过提供自定义分配器::构造...

当调整到较小的大小时,向量容量永远不会减少,因为这将使所有迭代器失效,而不仅仅是那些被POP的等价序列所失效的迭代器。[医]回传%28%29次电话。

二次

#include <iostream> #include <vector> int main() { std::vector<int> c = {1, 2, 3}; std::cout << "The vector holds: "; for(auto& el: c) std::cout << el << ' '; std::cout << '\n'; c.resize(5 std::cout << "After resize up 5: "; for(auto& el: c) std::cout << el << ' '; std::cout << '\n'; c.resize(2 std::cout << "After resize down to 2: "; for(auto& el: c) std::cout << el << ' '; std::cout << '\n'; }

二次

产出:

二次

The vector holds: 1 2 3 After resize up 5: 1 2 3 0 0 After resize down to 2: 1 2

二次

另见

sizereturns the number of elements (public member function)
insertinserts elements (public member function)
eraseerases elements (public member function)

© cppreference.com

在CreativeCommonsAttribution下授权-ShareAlike未移植许可v3.0。

http://en.cpPreference.com/w/cpp/容器/Vectoral/Resignate