Movatterモバイル変換


[0]ホーム

URL:


cppreference.com
Namespaces
Variants
    Actions

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

      From cppreference.com
      <cpp‎ |string‎ |basic string
       
       
       
      std::basic_string
       
      size_type capacity()const;
      (noexcept since C++11)
      (constexpr since C++20)

      Returns the number of characters that the string has currently allocated space for.

      Contents

      [edit]Parameters

      (none)

      [edit]Return value

      Capacity of the currently allocated storage, i.e. the storage available for storing elements.

      [edit]Complexity

      Constant.

      [edit]Notes

      Memory locations obtained from the allocator but not available for storing any element are not counted in the allocated storage. Note that the null terminator is not an element of thestd::basic_string.

      [edit]Example

      Run this code
      #include <iomanip>#include <iostream>#include <string> void show_capacity(std::stringconst& 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();}}

      Possible output:

      "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         231     60         261     120        2121    240        2241    480        2

      [edit]See also

      returns the number of characters
      (public member function)[edit]
      reserves storage
      (public member function)[edit]
      Retrieved from "https://en.cppreference.com/mwiki/index.php?title=cpp/string/basic_string/capacity&oldid=177139"

      [8]ページ先頭

      ©2009-2025 Movatter.jp