std::string max_size() 方法
- 自 C++20 起
- 自 C++11 起
- 直到 C++11
// Const version only
constexpr bool max_size() const noexcept;
// Const version only
bool max_size() const noexcept;
// Const version only
bool max_size() const;
返回容器由于系统或库实现限制而能够容纳的最大元素数量,即最大容器的 std::distance(begin(), end())
。
参数
(无)
返回值
容器可以容纳的最大元素数量。
复杂度
常数 - O(1)。
备注
此值通常反映容器大小的理论限制,最多为 std::numeric_limits<difference_type>::max()
。在运行时,容器的大小可能会受限于可用 RAM 的数量,其值小于max_size()
。
示例
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";
}
可能输出
Maximum size of a string is 9223372036854775807 (0x7fffffffffffffff), pointer size: 64 bits