名稱空間
變體
操作

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

來自 cppreference.com
< cpp‎ | string‎ | basic_string
 
 
 
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()(如果 CharTchar,則為 '\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 << "Basic functionality:\n"
              << "Shorten:\n"
              << "1. Before: " << std::quoted(long_string) << '\n';
    long_string.resize(desired_length);
    std::cout << "2. After:  " << std::quoted(long_string) << '\n';
 
    std::cout << "Lengthen with a given value 'a':\n"
              << "3. Before: " << std::quoted(short_string) << '\n';
    short_string.resize(desired_length, 'a');
    std::cout << "4. After:  " << std::quoted(short_string) << '\n';
 
    std::cout << "Lengthen with char() == " << static_cast<int>(char()) << '\n'
              << "5. Before: " << std::quoted(short_string) << '\n';
    short_string.resize(desired_length + 3);
    std::cout << "6. After:  \"";
    for (char c : short_string)
        std::cout << (c == char() ? '@' : c);
    std::cout << "\"\n\n";
 
    std::cout << "Errors:\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& ex)
    {
        std::cout << "1. Exception: " << ex.what() << '\n';
    }
 
    try
    {
        // size is OK, no length_error
        // (may throw bad_alloc)
        s.resize(s.max_size(), 'x');
    }
    catch (const std::bad_alloc& ex)
    {
        std::cout << "2. Exception: " << ex.what() << '\n';
    }
 
    try
    {
        // size is BAD, throw length_error
        s.resize(s.max_size() + 1, 'x');
    }
    catch (const std::length_error& ex)
    {
        std::cout << "3. Length error: " << ex.what() << '\n';
    }
}

可能的輸出

Basic functionality:
Shorten:
1. Before: "Where is the end?"
2. After:  "Where is"
Lengthen with a given value 'a':
3. Before: "H"
4. After:  "Haaaaaaa"
Lengthen with char() == 0
5. Before: "Haaaaaaa"
6. After:  "Haaaaaaa@@@"
 
Errors:
1. Exception: std::bad_alloc
2. Exception: std::bad_alloc
3. Length error: basic_string::_M_replace_aux

[編輯] 缺陷報告

下列更改行為的缺陷報告追溯地應用於以前出版的 C++ 標準。

缺陷報告 應用於 釋出時的行為 正確的行為
LWG 847 C++98 沒有異常安全保證 添加了強異常安全保證
LWG 2250 C++98
count > max_size()true
在這種情況下總是丟擲異常

[編輯] 參閱

返回字元數
(public member function) [編輯]
預留儲存空間
(public member function) [編輯]
透過釋放未使用的記憶體來減少記憶體使用
(public member function) [編輯]