std::basic_string<CharT,Traits,Allocator>::resize
From cppreference.com
< cpp | string | 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 | - | 文字列の新しいサイズ |
| 文字 | - | 新しい文字を初期化するために使用する文字 |
[編集] 例外
std::length_error: count > max_size() の場合。対応する 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++標準に遡って適用されました。
| DR | 適用対象 | 公開された動作 | 正しい動作 |
|---|---|---|---|
| LWG 847 | C++98 | 例外安全性保証がなかった | 強力な例外安全性保証を追加 |
| LWG 2250 | C++98 | 次に該当する場合、動作は未定義でした。 count > max_size() が true の場合 |
この場合、常に例外をスローします。 |
[編集] 関連項目
| 文字数を返す (public member function) | |
| ストレージを予約する (public member function) | |
| (DR*) |
未使用のメモリを解放してメモリ使用量を削減する (public member function) |