## What’s the size limit of a vector?

Use *std::vector::max_size()* function.

Don’t confuse this function with *std::vector::capacity()* and *std::vector::size()* functions. *vector::capacity()* tells us when a vector will be reallocated and *vector::size()* tells us the count of elements inserted into a vector.

Source code of *vector::max_size* looks like this…

_SIZT max_size() const _THROW0() { // estimate maximum array size _SIZT _Count = (_SIZT)(-1) / sizeof (_Ty); return (0 < _Count ? _Count : 1); }[/sourcecode] -1 is being cast to _SIZT and then divided by the sizeof the vector type. Have a look at the following illustration... [sourcecode language='cpp']template<class T> void PrintVectorMaxSize( std::vector<t>& Obj) { const std::vector</t><t>::size_type MaxSize = Obj.max_size(); std::cout < < "Max elements that can be inserted into a vector having elements of size '" << sizeof( T ) << "' is: " << MaxSize << std::endl; } int main() { PrintVectorMaxSize( std::vector<BYTE>() ); PrintVectorMaxSize( std::vector<int>() ); PrintVectorMaxSize( std::vector<double>() ); PrintVectorMaxSize( std::vector<char *>() ); }

Here is the output for the above program…

Max elements that can be inserted into a vector having elements of size ‘1’ is: 4294967295

Max elements that can be inserted into a vector having elements of size ‘4’ is: 1073741823

Max elements that can be inserted into a vector having elements of size ‘8’ is: 536870911

Max elements that can be inserted into a vector having elements of size ‘4’ is: 1073741823

PS: Please edit those html tags inserted by code formatter before compilation.

Technorati Tags: CPlusplus, Finding out size limit of a vector, Maximum elements that can be inserted into a vector, max_size, Size limit of a vector, std::vector, VC++, vector

Quite helpful 🙂