user14101590
user14101590

Reputation:

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

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 */

Upvotes: 3

Views: 1870

Answers (3)

ayush kadyan
ayush kadyan

Reputation: 1

size () tell the number of elements in array and max_size() tell the capacity of array but as in array we have not ability to decide which data item is valid or which not . as we write array<int,5>={1}; then array built is {1,0,0,0,0}; then it can not consider 0's as invalid items . therefore size() and max_size() give same answere as in when we even make array without putting initializing it then also it have garbage value and it consider then as elements in array then give same output for size() and max_size() . theoretically size() give number of elements and max_size() give capacity but array have element at all index from starting ether garbage value , 0 or putted by user therefore we get same output.

Upvotes: -2

eerorika
eerorika

Reputation: 238361

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.

Upvotes: 9

user8616480
user8616480

Reputation:

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

Upvotes: -2

Related Questions