Namespaces
Variants

std::basic_string<CharT,Traits,Allocator>:: resize

From cppreference.net
std::basic_string
void resize ( size_type count ) ;
(1) (自 C++20 起为 constexpr)
void resize ( size_type count, CharT ch ) ;
(2) (自 C++20 起为 constexpr)

将字符串大小调整为包含 count 个字符。

如果当前大小小于 count ,则会追加额外字符:

1) 将附加字符初始化为 CharT ( ) (若 CharT char 则为 ' \0 ' )。
2) 将追加的字符初始化为 ch

如果当前大小大于 count ,字符串将被缩减至其前 count 个元素。

目录

参数

count - 字符串的新大小
ch - 用于初始化新字符的字符

异常

count > max_size ( ) true ,则抛出 std::length_error 。 由对应 Allocator 抛出的任何异常。

若因任何原因抛出异常,此函数不产生任何效果( 强异常安全保证 )。

示例

#include <iomanip>
#include <iostream>
#include <stdexcept>
int main()
{
    const unsigned desired_length{8};
    std::string long_string("Where is the end?");
    std::string short_string("H");
    std::cout << "基本功能:\n"
              << "缩短:\n"
              << "1. 之前:" << std::quoted(long_string) << '\n';
    long_string.resize(desired_length);
    std::cout << "2. 之后:" << std::quoted(long_string) << '\n';
    std::cout << "使用给定值 'a' 延长:\n"
              << "3. 之前:" << std::quoted(short_string) << '\n';
    short_string.resize(desired_length, 'a');
    std::cout << "4. 之后:" << std::quoted(short_string) << '\n';
    std::cout << "使用 char() == " << static_cast<int>(char()) << '\n'
              << "5. 之前:" << std::quoted(short_string) << '\n';
    short_string.resize(desired_length + 3);
    std::cout << "6. 之后:\"";
    for (char c : short_string)
        std::cout << (c == char() ? '@' : c);
    std::cout << "\"\n\n";
    std::cout << "错误处理:\n";
    std::string s;
    try
    {
        // 大小正常,不会抛出 length_error
        //(可能抛出 bad_alloc)
        s.resize(s.max_size() - 1, 'x');
    }
    catch (const std::bad_alloc& ex)
    {
        std::cout << "1. 异常:" << ex.what() << '\n';
    }
    try
    {
        // 大小正常,不会抛出 length_error
        //(可能抛出 bad_alloc)
        s.resize(s.max_size(), 'x');
    }
    catch (const std::bad_alloc& ex)
    {
        std::cout << "2. 异常:" << ex.what() << '\n';
    }
    try
    {
        // 大小异常,抛出 length_error
        s.resize(s.max_size() + 1, 'x');
    }
    catch (const std::length_error& ex)
    {
        std::cout << "3. 长度错误:" << ex.what() << '\n';
    }
}

可能的输出:

基本功能:
缩短:
1. 之前:"Where is the end?"
2. 之后:"Where is"
使用给定值 'a' 延长:
3. 之前:"H"
4. 之后:"Haaaaaaa"
使用 char() == 0
5. 之前:"Haaaaaaa"
6. 之后:"Haaaaaaa@@@"
错误处理:
1. 异常:std::bad_alloc
2. 异常:std::bad_alloc
3. 长度错误:basic_string::_M_replace_aux

缺陷报告

以下行为变更缺陷报告被追溯应用于先前发布的C++标准。

缺陷报告 适用标准 发布时行为 正确行为
LWG 847 C++98 未提供异常安全保证 增加强异常安全保证
LWG 2250 C++98
count > max_size ( ) true 时行为未定义
此情况下始终抛出异常

参见

返回字符数量
(公开成员函数)
预留存储空间
(公开成员函数)
通过释放未使用的内存来减少内存使用
(公开成员函数)