std::basic_string<CharT,Traits,Allocator>::resize
提供: cppreference.com
< cpp | string | basic string
(1) | ||
void resize( size_type count ); |
(C++20未満) | |
constexpr void resize( size_type count ); |
(C++20以上) | |
(2) | ||
void resize( size_type count, CharT ch ); |
(C++20未満) | |
constexpr void resize( size_type count, CharT ch ); |
(C++20以上) | |
count
個の文字を持つように文字列のサイズを変更します。
現在のサイズが count
より小さい場合、追加の文字が追加されます。
現在のサイズが count
より大きい場合、文字列はその最初の count
個の要素に減らされます。
(1) は新しい文字を CharT() で初期化し、 (2) は新しい文字を ch
で初期化します。
目次 |
[編集] 引数
count | - | 文字列の新しいサイズ |
ch | - | 新しい文字を初期化するための文字 |
[編集] 戻り値
(なし)
[編集] 例外
count > max_size() の場合 std::length_error。
対応する Allocator
によって投げられるあらゆる例外。
何らかの理由で例外が投げられた場合、この関数は効果を持ちません (強い例外保証)。 (C++11以上)
[編集] 例
Run this code
#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"; } } }
出力例:
Basic functionality: Before: "Where is the end?" After: "Where is" Before: "Ha" After: "Haaaaaaa" Errors: 1. bad alloc 2. bad alloc 3. length error
[編集] 計算量
文字列のサイズに比例。
[編集] 関連項目
文字数を返します (パブリックメンバ関数) |