I have a huge 3d vector where I store double values. In order to increase the performance I wanted to reserve the number of elements in advance as I know them before processing;however, I couldn't really figure it out how reserve&clear&erase work in this case.
I have implemented a small program which has 2d vector in this case, pls see the code snippet below:`
for(int counter = 0; counter < 2; counter++){
cout << "Counter-> " << counter << endl;
vector<vector<double> > vec2D;
vec2D.reserve(2);
// assign values to the vec
for(int i = 0; i < 2; i++){
vec2D[i].reserve(5);
for(int j = 0; j < 5; j++){
vec2D[i][j] = j;
}
}
// print the vector content
for(int i = 0; i < 2; i++){
for(int j = 0; j < 5; j++){
cout << vec2D[i][j] << "\t";
}
vec2D[i].clear();
cout << endl;
}
vec2D.clear();
}
When I run this code snippet it iterates thorugh the for loop just for once where it should do it twice; however, when I declare the vector outside of the for loop it does iterate twice. The output of the above snippet is:
Counter-> 0
0 1 2 3 4
0 1 2 3 4
Counter-> 1
Could you please make it clear how it actually should be in this case and how it works.
Thanks in advance.