Reputation: 5
Why can't this code handle n=100000000
(8 zeros)?
The code will be terminated by this error:
terminate called after throwing an instance of 'std::bad_alloc'
So, the word "DONE" won't be printed out.
using namespace std;
int main()
{
vector <long long> v1;
long long n; cin>>n;
for(long long i=0;i<n;i++){
v1.push_back(i+1);
}
cout<<"DONE"<<endl;
}
Although the maximum size of v1
is 536870911.
Upvotes: 0
Views: 2385
Reputation: 596216
std::vector
contains a pointer to a single dynamically allocated contiguous array. As you call push_back()
in your loop, that array has to grow over time whenever the vector's size()
exceeds is capacity()
. As the array grows large, it becomes more difficult for a new larger contiguous array to be allocated to copy the old array elements into. Eventually, the array is so large that a new copy simply can't be allocated anymore, and thus std::bad_alloc
gets thrown.
To avoid all of those reallocations while looping, call the vector's reserve()
method before entering the loop:
int main() {
vector <long long> v1;
long long n; cin>>n;
v1.reserve(n); // <-- ADD THIS!
for(long long i = 0; i < n; ++i){
v1.push_back(i+1);
}
cout<<"DONE"<<endl;
}
That way, the array is allocated only 1 time.
Upvotes: 1
Reputation: 238351
What is the maximum size of a vector?
Depends on several factors. Here are some upper limits:
std::vector::size_type
std::vector::max_size
The address space isn't an issue in 64 bit world.
Note that the size of the element type affects the number of elements that fit in a given range of memory.
The most likely the strictest limit in your case was the available memory. 536870911 is one long long
short of 4 gigabytes.
Upvotes: 7
Reputation: 334
From cppref max_size() docs:
This value typically reflects the theoretical limit on the size of the container ...
At runtime, the size of the container may be limited to a value smaller than max_size() by the amount of RAM available.
Upvotes: 3