C++ std::array::max_size
The std::array::max_size
function returns the maximum number of elements that the array can hold. This function is useful for determining the fixed size of a std::array
, which is known at compile time. For std::array
, the value returned by max_size()
is always equal to the size of the array.
Syntax of std::array::max_size
constexpr size_type max_size() const noexcept;
Parameters
The std::array::max_size
function does not take any parameters.
Return Value
Returns the maximum number of elements that the array can hold, which is equal to the size of the array as defined at compile time. The return type is size_type
.
Examples for std::array::max_size
Example 1: Getting the Maximum Size of a std::array
This example demonstrates how to use the max_size
function to determine the maximum number of elements a std::array
can hold:
#include <iostream>
#include <array>
int main() {
std::array<int, 10> arr;
std::cout << "The maximum size of the array is: " << arr.max_size() << std::endl;
return 0;
}
Explanation:
- Define a
std::array
: Astd::array
of size 10 is created. - Use
max_size()
: Themax_size()
function returns the fixed size of the array, which is 10 in this case. - Output the size: The maximum size of the array is printed to the console using
std::cout
.
Output:
The maximum size of the array is: 10
Example 2: Comparing std::array::max_size with std::vector
This example shows how the max_size
of a std::array
differs from the dynamically determined capacity of a std::vector
:
#include <iostream>
#include <array>
#include <vector>
int main() {
std::array<int, 5> arr;
std::vector<int> vec(5);
std::cout << "Maximum size of std::array: " << arr.max_size() << std::endl;
std::cout << "Capacity of std::vector: " << vec.capacity() << std::endl;
return 0;
}
Explanation:
- Define a
std::array
: An array of size 5 is defined, and itsmax_size()
function is called to get the maximum size, which is always 5. - Define a
std::vector
: A vector with an initial size of 5 is created, and its capacity is retrieved using thecapacity()
function, which may vary depending on the implementation. - Output the results: The maximum size of the array and the capacity of the vector are printed for comparison.
Output:
Maximum size of std::array: 5
Capacity of std::vector: 5
Exception Handling in std::array::max_size
The std::array::max_size
function does not throw exceptions as it is marked noexcept
. This ensures safe access to the maximum size of the array.