gia
gia

Reputation: 757

C++ Vector<int> array initialization

Given the following code:

vector<int> A[1000000];
for( int i = 0; i < 1000000; i++ ){
    A[i].clear();
}

I am running it on an automated terminal that has test cases run with my code, so I can't get full debug messages. I don't get any errors, and the program seems to run fine with single test cases. However when I run against the full set I pass/fail test cases randomly (one time I may pass the first 3, another I pass everything but them, another I only pass the second, etc). I want to make sure this kind of initialization would get rid of "undefined" values on the array (eg char *buffer = new char[100]; buffer[0] = 0;) so that it is not a cause of random crashes.

sizeof(A) == 24000000 (~23MB), sizeof(int) == 4. I only add up to 1 million integers to these vectors (in total), so in the worst tests, each vector could be a one element vector, or a single vector could have 1 million integers, while the rest remains empty.

Do I have to call a destructor? I assumed not since I never called new, but I'm new to STL. Finally it could be not an issue with my code but the tester, but still, want to make sure this is fine on my side.

Upvotes: 1

Views: 2825

Answers (2)

VivekD
VivekD

Reputation: 328

In place of for loop use below code

std::fill(A.begin(), A.end(), 0);

Upvotes: 0

cthl
cthl

Reputation: 409

I think this is a stack overflow, as M.M suggested. The line

std::vector<int> A[1000000];

creates a million vector objects on the stack, which is too much. On my machine, the example failed for one million vectors, but it worked fine for one thousand.

Upvotes: 6

Related Questions