Namespaces
Variants

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

From cppreference.net
std::basic_string
size_type capacity ( ) const ;
(C++11부터 noexcept)
(C++20부터 constexpr)

현재 문자열이 공간을 할당받은 문자 수를 반환합니다.

목차

매개변수

(없음)

반환값

현재 할당된 저장 공간의 용량, 즉 요소를 저장하는 데 사용 가능한 저장 공간입니다.

복잡도

상수.

참고 사항

할당자로부터 얻었지만 어떤 요소도 저장하는 데 사용할 수 없는 메모리 위치는 할당된 저장 공간에 포함되지 않습니다. 널 종결자는 std::basic_string 의 요소가 아님에 유의하십시오.

예제

#include <iomanip>
#include <iostream>
#include <string>
void show_capacity(std::string const& s)
{
    std::cout << std::quoted(s) << " has capacity " << s.capacity() << ".\n";
}
int main()
{
    std::string s{"Exemplar"};
    show_capacity(s);
    s += " is an example string.";
    show_capacity(s);
    s.clear();
    show_capacity(s);
    std::cout << "\nDemonstrate the capacity's growth policy."
                 "\nSize:  Capacity:  Ratio:\n" << std::left;
    std::string g;
    auto old_cap{g.capacity()};
    for (int mark{}; mark != 5; ++mark)
    {
        while (old_cap == g.capacity())
            g.push_back('.');
        std::cout << std::setw( 7) << g.size()
                  << std::setw(11) << g.capacity()
                  << std::setw(10) << g.capacity() / static_cast<float>(old_cap) << '\n';
        old_cap = g.capacity();
    }
}

가능한 출력:

"Exemplar" has capacity 15.
"Exemplar is an example string." has capacity 30.
"" has capacity 30.
Demonstrate the capacity's growth policy.
Size:  Capacity:  Ratio:
16     30         2
31     60         2
61     120        2
121    240        2
241    480        2

참고 항목

문자 수를 반환합니다
(public member function)
저장 공간을 예약합니다
(public member function)