4

What is the difference between size() and max_size() functions for std: :array in C++?

  array<int,5> arr{ 1, 2, 3, 4, 5 }; 
  cout << arr.size(); 
  /* Output : 5 */ 
  
 array<int, 5> arr{ 1, 2, 3, 4, 5 }; 
 cout << arr.max_size(); 
 /* Output : 5 */
1
  • 2
    size and max_size are part of "interface" of most containers. For fixed sized std::array, there are indeed the same; for std::vector, there would be different. Commented Sep 23, 2021 at 12:24

2 Answers 2

9

What is the difference between size() and max_size() functions for std: :array in C++?

The latter has prefix max_. There is no other practical difference between them for std::array.

The difference is conceptual. size is the current number of elements in the container, and max_size is a theoretical upper bound to how many elements the container could have. Since the number of elements in std::array is constant, the current number of elements is exactly the same as the number of elements there can ever be. For other containers, there is a practical difference.

Using the max_size member function of std::array is conceptually silly. It exists so that std::array conforms to the Container concept (e.g. named requirement), which allows it to be used uniformly with other containers, which is useful within templates.

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

Comments

-2

i think max_size() refers to the capacity of the array and not the actual size of the array.

2 Comments

while arrays are similar to other containers by having a max_size they don't have capacity.
Furthermore, in case of a container that does have a capacity such as std::vector, std::vector::max_size has no correllaction with std::vector::capacity.

Your Answer

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