Question is about variables inside the loop. How does it works?
Similar questions:
one
two
code:
for ( i = 0 ; i < 3 ; i++ ) {
vector<int> vint;
vint.push_back(i);
cout << "vecor size is: " << vint.size() << endl;
for ( j = 0 ; j < vint.size() ; j++ ) {
cout << "vint[" << j << "] = " << vint[j] << endl;
}
}
above code gives next output:
vecor size is: 1
vint[0] = 0
vecor size is: 1
vint[0] = 1
vecor size is: 1
vint[0] = 2
It looks like that in the end of each iteration method sdt::vector::erase is called or somehow vint becomes again empty. How does it work, and how did you figure out it? thank you!
UPDATE:
If I want different vector in each iteration what is better:
declare vint in the loop
or declare it before the loop and use clear() in the end of the loop?
Variables in the statement of the for-loop are constructed and destructed in each iteration. In your particular case this would involve memory allocation and deallocation for each iteration. If you need a different vector each iteration you’d still be best off declaring it prior to the loop (or in the loop’s initialization) and
clear()ing it at the end of the loop (or in the loop’s advance).