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

std::basic_string::resize

void resize( size_type count );

(1)

void resize( size_type count, CharT ch );

(2)

调整要包含的字符串的大小。count人物。

如果当前大小小于count,附加其他字符。

如果当前大小大于count,字符串被缩减为第一个字符串。count元素。

第一个版本将新字符初始化为CharT(),第二个版本将新字符初始化为ch...

参数

count

-

new size of the string

ch

-

character to initialize the new characters with

返回值

%280%29

例外

std::length_error如果count > max_size().由相应的Allocator...

如果出于任何原因引发异常,则此函数没有效果%28强异常保证%29。%28自C++11%29。

二次

代码语言:javascript
复制
#include <iostream>
#include <stdexcept>
 
int main()
{
    std::cout << "Basic functionality:\n";
    const unsigned  desired_length(8);
    std::string     long_string( "Where is the end?" );
    std::string     short_string( "Ha" );
 
    // Shorten
    std::cout << "Before: \"" << long_string << "\"\n";
    long_string.resize( desired_length );
    std::cout << "After: \"" << long_string <<  "\"\n";
 
    // Lengthen
    std::cout << "Before: \"" << short_string <<  "\"\n";
    short_string.resize( desired_length, 'a' );
    std::cout << "After: \"" << short_string <<  "\"\n";
 
    std::cout  << "\nErrors:\n";
    {
        std::string s;    
 
        try {
            // size is OK, no length_error
            // (may throw bad_alloc)
            s.resize(s.max_size() - 1, 'x');
        } catch (const std::bad_alloc&) {
            std::cout << "1. bad alloc\n";
        }
 
        try {
            // size is OK, no length_error
            // (may throw bad_alloc)
            s.resize(s.max_size(), 'x');
        } catch (const std::bad_alloc& exc) {
            std::cout << "2. bad alloc\n";
        }
 
        try {
            // size is BAD, throw length_error
            s.resize(s.max_size() + 1, 'x');
        } catch (const std::length_error&) {
            std::cout << "3. length error\n";
        }
     }
}

二次

可能的产出:

二次

代码语言:javascript
复制
Basic functionality:
Before: "Where is the end?"
After: "Where is"
Before: "Ha"
After: "Haaaaaaa"
 
Errors:
1. bad alloc
2. bad alloc
3. length error

二次

复杂性

在字符串的大小上是线性的。

另见

sizelength

returns the number of characters (public member function)

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

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

扫码关注腾讯云开发者

领取腾讯云代金券