std::basic_string<CharT,Traits,Allocator>:: resize
|
void
resize
(
size_type count
)
;
|
(1) | (constexpr since C++20) |
|
void
resize
(
size_type count, CharT ch
)
;
|
(2) | (constexpr since C++20) |
文字列のサイズを count 文字に変更します。
現在のサイズが count より小さい場合、追加の文字が付加されます:
CharT
が
char
の場合)。
現在のサイズが count より大きい場合、文字列は最初の count 要素に縮小されます。
目次 |
パラメータ
| count | - | 文字列の新しいサイズ |
| ch | - | 新しい文字を初期化するための文字 |
例外
std::length_error
count
count
>
max_size
(
)
が
true
の場合。
対応する
Allocator
によってスローされる例外。
何らかの理由で例外がスローされた場合、この関数は何も効果を及ぼしません( strong exception safety guarantee )。
例
#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 { // サイズはOK、length_errorなし // (bad_allocをスローする可能性あり) s.resize(s.max_size() - 1, 'x'); } catch (const std::bad_alloc& ex) { std::cout << "1. 例外: " << ex.what() << '\n'; } try { // サイズはOK、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++規格に対して遡及的に適用されました。
| DR | 適用対象 | 公開時の動作 | 正しい動作 |
|---|---|---|---|
| LWG 847 | C++98 | 例外安全性保証がなかった | 強い例外安全性保証を追加 |
| LWG 2250 | C++98 |
動作は未定義だった(
count > max_size ( ) が true の場合) |
この場合、常に例外をスローする |
関連項目
|
文字数を返す
(公開メンバ関数) |
|
|
ストレージを予約する
(公開メンバ関数) |
|
|
(
DR*
)
|
未使用メモリを解放してメモリ使用量を削減する
(公開メンバ関数) |