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

std::basic_string::reserve

void reserve( size_type new_cap = 0 );

通知std::basic_string对象的计划更改大小,以便它可以适当地管理存储分配。

  • 如果new_cap大于当前capacity(),则分配新存储空间,以及capacity()等于或大于new_cap...
  • 如果new_cap比电流小capacity(),这是一个非绑定收缩请求。
  • 如果new_cap比电流小size(),这是一个非绑定收缩到适合的请求,相当于shrink_to_fit()%28自C++11%29。

如果发生容量更改,则所有迭代器和引用,包括过去的结束迭代器,都将失效。

参数

new_cap

-

new capacity of the string

返回值

%280%29

例外

抛出std::length_error如果new_cap大于max_size()...

引发的任何异常。std::allocator_traits<Allocator>::allocate(),如std::bad_alloc...

复杂性

最多是线性的size()那根绳子。

二次

代码语言:javascript
复制
#include <cassert>
#include <string>
 
int main()
{
    std::string s;
    std::string::size_type new_capacity{ 100u };
    assert(new_capacity > s.capacity());
 
    s.reserve(new_capacity);
    assert(new_capacity <= s.capacity());
}

二次

另见

capacity

returns the number of characters that can be held in currently allocated storage (public member function)

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

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

扫码关注腾讯云开发者

领取腾讯云代金券