Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

std: :array -- difference between size() and max_size()

Tags:

c++

stl

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 Answers

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.

like image 113
eerorika Avatar answered Oct 29 '25 18:10

eerorika



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!