Skip to main content

std::string max_size() method

// Const version only
constexpr bool max_size() const noexcept;

Returns the maximum number of elements the container is able to hold due to system or library implementation limitations, i.e. std::distance(begin(), end()) for the largest container.

Parameters

(none)

Return value

Maximum number of elements the container can hold.

Complexity

Constant - O(1).

Notes

This value typically reflects the theoretical limit on the size of the container, at most std::numeric_limits<difference_type>::max(). At runtime, the size of the container may be limited to a value smaller than max_size() by the amount of RAM available.

Example

Main.cpp
#include <iostream>
#include <string>
#include <climits>

int main()
{
std::string s;
std::cout
<< "Maximum size of a string is " << s.max_size() << " ("
<< std::hex << std::showbase << s.max_size()
<< "), pointer size: " << std::dec
<< CHAR_BIT*sizeof(void*) << " bits\n";
}
Possible output

Maximum size of a string is 9223372036854775807 (0x7fffffffffffffff), pointer size: 64 bits
This article originates from this CppReference page. It was likely altered for improvements or editors' preference. Click "Edit this page" to see all changes made to this document.
Hover to see the original license.

std::string max_size() method

// Const version only
constexpr bool max_size() const noexcept;

Returns the maximum number of elements the container is able to hold due to system or library implementation limitations, i.e. std::distance(begin(), end()) for the largest container.

Parameters

(none)

Return value

Maximum number of elements the container can hold.

Complexity

Constant - O(1).

Notes

This value typically reflects the theoretical limit on the size of the container, at most std::numeric_limits<difference_type>::max(). At runtime, the size of the container may be limited to a value smaller than max_size() by the amount of RAM available.

Example

Main.cpp
#include <iostream>
#include <string>
#include <climits>

int main()
{
std::string s;
std::cout
<< "Maximum size of a string is " << s.max_size() << " ("
<< std::hex << std::showbase << s.max_size()
<< "), pointer size: " << std::dec
<< CHAR_BIT*sizeof(void*) << " bits\n";
}
Possible output

Maximum size of a string is 9223372036854775807 (0x7fffffffffffffff), pointer size: 64 bits
This article originates from this CppReference page. It was likely altered for improvements or editors' preference. Click "Edit this page" to see all changes made to this document.
Hover to see the original license.