C++ vector max_size();
max_size()
is the theoretical maximum number of items that could be put in your vector. On a 32-bit system, you could in theory allocate 4Gb == 2^32 which is 2^32 char
values, 2^30 int
values or 2^29 double
values. It would appear that your implementation is using that value, but subtracting 1.
Of course, you could never really allocate a vector that big on a 32-bit system; you'll run out of memory long before then.
There is no requirement on what value max_size()
returns other than that you cannot allocate a vector bigger than that. On a 64-bit system it might return 2^64-1 for char
, or it might return a smaller value because the system only has a limited memory space. 64-bit PCs are often limited to a 48-bit address space anyway.
Simply get the answer by
std::vector<dataType> v;
std::cout << v.max_size();
Or we can get the answer by (2^nativePointerBitWidth)/sizeof(dataType) - 1
. For example, on a 64 bit system, long long
is (typically) 8 bytes wide, so we have (2^64)/8 - 1 == 2305843009213693951
.
max_size() returns
the maximum potential size the vector could reach due to system or library implementation limitations.
so I suppose that the maximum value is implementation dependent. On my machine the following code
std::vector<int> v;
cout << v.max_size();
produces output:
4611686018427387903 // built as 64-bit target
1073741823 // built as 32-bit target
so the formula 2^(64-size(type))-1 looks correct for that case as well.