Whenever I try with max_size() and size() funtion of std::array, I get same results, I wanted to know if there could be a situation where two of them give different results.
-
4From en.cppreference.com/w/cpp/container/array/max_size: "Because each std::array<T, N> is a fixed-size container, the value returned by max_size equals N (which is also the value returned by size)".Jarod42– Jarod422018-01-19 18:15:14 +00:00Commented Jan 19, 2018 at 18:15
5 Answers
Those two functions will always return the same value, namely N for an std::array<T, N>.
They are provided for consistency with other containers, for which the values will differ (e.g. std::vector).
3 Comments
There is no such example, because arrays are fixed-size containers. Their current size is the same as their maximum size because they cannot grow or shrink.
The reason max_size() is there at all is to let you use std::array in a way that is interchangeable with other containers from the C++ Standard Library.
There is no reason to use max_size() in contexts when your program knows the type of the container to be std::array.
Comments
std::array::max_size() returns the maximum number of elements that array can ever hope to contain. The size of an array is a compile-time constant and part of its type. It can only ever hold exactly that number of elements. The number of elements it contains and the number of elements it could contain are the same thing for std::array.
That particular function doesn't add much to std::array, but it exists for compatibility with other containers, which can store a variable number of elements. Consider the case where a function template expects some container type as argument. You may be interested in knowing that container's maximum storage capacity, rather it's std::array or another container.
Comments
For std::array both functions are equal as stated in documentation. Despite duplication std::array::max_size() exists because std::array must satisfy concept Container which requires such method.