views:

97

answers:

3
+4  A: 

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.

Vladimir
+5  A: 

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; 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.

Anthony Williams
Thanks antony!!!
Kundan
A: 

Access to vector elements requires offset from the beginning of the vector. Offset, like pointer, has 32 bits size on 32-bit system, and 64 bits size on 64-bit system. Since int type has 4 bytes length, max vector capacity is (2^32)/4 - 1, etc.

For 64 bits I expect the following results: (2^64) -1, (2^62) -1, (2^61) -1.

Practical conclusion: always use size_t type for array index.

Alex Farber
No, don't. Use `std::vector<T>::size_type` for an array index. It's the type specifically defined for that purpose.
MSalters
@Alex Thanks for ans.yes you are correct... u can use int instead of size_type
Kundan