C++ Standard Library C++ STL Library

C++ <vector> - max_size() Function



The C++ vector::max_size function returns the maximum number of elements the vector can hold. It returns the maximum potential size the vector can reach due to known system or library implementation limitations.

Syntax

size_type max_size() const;
size_type max_size() const noexcept;

Parameters

No parameter is required.

Return Value

Maximum number of elements that can be held in a vector.

Time Complexity

Constant i.e, Θ(1).

Example:

In the example below, the vector::max_size function is used to find out the maximum number of elements that a vector can hold.

#include <iostream>
#include <vector>
using namespace std;
 
int main (){
  vector<int> MyVector{10, 20, 30, 40, 50};
  vector<int>::iterator it;

  cout<<"The vector contains:";
  for(it = MyVector.begin(); it != MyVector.end(); ++it)
    cout<<" "<<*it;

  cout<<"\nVector size is: "<<MyVector.size()<<"\n";
  cout<<"Vector capacity is: "<<MyVector.capacity()<<"\n";
  cout<<"Maximum size of the Vector: "<<MyVector.max_size()<<"\n"; 
  return 0;
}

A possible output could be:

The vector contains: 10 20 30 40 50
Vector size is: 5
Vector capacity is: 5
Maximum size of the Vector: 2305843009213693951

❮ C++ <vector> Library