On an online course I am learning about vectors. In one of the examples they explained that: std::vector::max_size()
should give me the maximum size the vector can reach. I decided to test it:
#include <iostream>
#include <exception>
#include <vector>
int main(void) {
std::vector <int> nums;
int max = nums.max_size();
std::cout << "Max: " << max << std::endl;
for (int i = 0; i < max; i++) {
try {
nums.push_back(i);
}
catch (std::bad_alloc ex) {
std::cerr << ex.what() << std::endl;
std::cout << "Failed at: " << i << std::endl;
break;
}
}
return 0;
}
And this is the result of running it:
Max: 1073741823
bad allocation
Failed at: 204324850
It was 869416973 ints short.
So I started googling it. Here I read that it returns the "the maximum potential size the container can reach", and adds "but the container is by no means guaranteed to be able to reach that size". I would have imagined that it would fail, but not by that much. It just got 1/5 of the way before failing. Why is std::vector::max_size
so off? And what I see of more importance, is there a way of really knowing the potential size of a vector?
max_size()
for containers is weird, and not particularly useful. With 20/20 hindsight, it probably should not exist.