Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ vector max_size();

On 32 bit System.

  1. std::vector<char>::max_size() returns 232-1, size of char — 1 byte
  2. std::vector<int>::max_size() returns 230-1, size of int — 4 byte
  3. std::vector<double>::max_size() returns 229-1, size of double — 8 byte

can anyone tell me max_size() depends on what?

and what will be the return value of max_size() if it runs on 64 bit system.

like image 204
Kundan Avatar asked Sep 28 '10 13:09

Kundan


People also ask

What is vector Max_size?

The vector::max_size() is a built-in function in C++ STL which returns the maximum number of elements that can be held by the vector container.

What is Max_size?

The set::max_size() is a built-in function in C++ STL which returns the maximum number of elements a set container can hold. Syntax: set_name.max_size() Parameters: This function does not accept any parameters. Return Value: This function returns the maximum number of elements a set container can hold.

Can you set a max size for a vector in C++?

You cannot set the maximum number of elements.

What does vector member size () do?

size() – Returns the number of elements in the vector. max_size() – Returns the maximum number of elements that the vector can hold. capacity() – Returns the size of the storage space currently allocated to the vector expressed as number of elements.


2 Answers

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.

like image 53
Anthony Williams Avatar answered Sep 19 '22 17:09

Anthony Williams


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.

like image 44
Vladimir Avatar answered Sep 20 '22 17:09

Vladimir