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.

- 2,747
- 10
- 38
- 53

- 303
- 3
- 7
-
4From http://en.cppreference.com/w/cpp/container/array/max_size: *"Because each std::array
is a fixed-size container, the value returned by max_size equals N (which is also the value returned by size)"*. – Jarod42 Jan 19 '18 at 18:15
5 Answers
That function exists for compatibility with other containers like std::vector
. For std::array
those two values will always be the same.

- 61,605
- 5
- 78
- 137
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
).

- 49,044
- 25
- 144
- 182
-
1I would say "consistency with other containers" is not proper description. Unfortunately all answers say that one way or another – Slava Jan 19 '18 at 20:07
-
@Slava How is it not a proper description? I don't see any value in dropping the phrase "container concept" here. – Baum mit Augen Jan 20 '18 at 13:44
-
1There are formal specifications (and I hope when they finally add concepts to the language they will be specified at that level) that certain containers must follow, yes I think describe that as "consistency with other" is not proper. – Slava Jan 22 '18 at 14:34
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
.

- 714,442
- 84
- 1,110
- 1,523
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.

- 49,044
- 25
- 144
- 182

- 28,148
- 6
- 56
- 87
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.

- 43,454
- 1
- 47
- 90