12

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.

1

5 Answers 5

15

That function exists for compatibility with other containers like std::vector. For std::array those two values will always be the same.

Sign up to request clarification or add additional context in comments.

Comments

8

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

I would say "consistency with other containers" is not proper description. Unfortunately all answers say that one way or another
@Slava How is it not a proper description? I don't see any value in dropping the phrase "container concept" here.
There 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.
4

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

2

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

2

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.