Namespaces
Variants

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

From cppreference.net
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 ( ) 로 초기화합니다 ( ' \0 ' 만약 CharT char 인 경우).
2) 추가된 문자들을 ch 로 초기화합니다.

현재 크기가 count 보다 크면, 문자열은 첫 번째 count 개의 요소로 축소됩니다.

목차

매개변수

count - 문자열의 새로운 크기
ch - 새로운 문자를 초기화하는 데 사용할 문자

예외

std::length_error 만약 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
    {
        // 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. 예외: " << 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. 예외: " << 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. 길이 오류: " << 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() 인 경우 동작이 정의되지 않았음 이 경우 항상 예외를 throw함

참고 항목

문자 수를 반환합니다
(public member function)
저장 공간을 예약합니다
(public member function)
사용되지 않는 메모리를 해제하여 메모리 사용량을 줄입니다
(public member function)