首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

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次电话。

二次

代码语言:javascript
复制
#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';
}

二次

产出:

二次

代码语言:javascript
复制
The vector holds: 1 2 3
After resize up 5: 1 2 3 0 0
After resize down to 2: 1 2

二次

另见

size

returns the number of elements (public member function)

insert

inserts elements (public member function)

erase

erases elements (public member function)

代码语言:txt
复制
 © cppreference.com

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

扫码关注腾讯云开发者

领取腾讯云代金券