[ Web Proxy ]
URL:
Viewing: http://ja.cppreference.com/cpp/string/basic_string/resize [Back]  [Original]

std::basic_string<CharT,Traits,Allocator>::resize - cppreference.com
cppreference.com

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

: cppreference.com
 
C++
(C++20)
(C++20)
(C++17)
(C++11)
(C++11)
(C++11)
 
 
std::basic_string
 
<tbody> </tbody> <tbody class="t-dcl-rev t-dcl-rev-num "> </tbody><tbody> </tbody> <tbody class="t-dcl-rev t-dcl-rev-num "> </tbody><tbody> </tbody>
(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)

#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


() [edit]

Web Proxy Viewer  |  New URL  |  Original Page