Thank you very much for the answer.
The reason that makes me think about checking the content of the vector is that even after I overwrite it, the same (strange) values remain. My purpose is to generate iteratively some random variables and put them in the two dimensional vector. I give you my code, maybe I am doing something wrong:
while (nbre_TTI_tempo != 0 )
{
srand(time(NULL)) ;
while (nbre_UE_tempo != 0 )
{
vect.clear() ;
nbre_PRB_tempo = nbre_PRB ;
while (nbre_PRB_tempo != 0)
{
value = rand() % 15 + 1 ; // generating random variables between 1 and 15
vect.push_back(value) ;
nbre_PRB_tempo -- ;
}
All_CQI.push_back(vect) ;
nbre_UE_tempo -- ;
}
// Do business
All_CQI.clear();
} .// end while
At the first round, everything goes well, but at the second one, this is what I find in the vector after the use of the method “clear”:
158429184
14
15
158429264
10
9
158429440
5
1
And when I try to overwrite it, I find:
158429184
14
15
158429264
10
9
158429440
5
1
Which are the same values as before using the method “push_back”.
Do you think I’m doing something wrong in my code?
Thank you very much in advance for your help.
For your purpose, if empty() returns true, you should trust that it is empty and SHOULD NOT check for individual elements. It is illegal to access the contents of an empty vector thus and can cause memory access errors.
The reason you find values is because the actual memory locations are not overwritten immediately- they are only marked as invalid. Until some other object is allocated the same memory, the data may remain as it is – but there is no way to be sure – the implementation is left to the compiler.
Looks like you are using the array operator[] to access the elements. To be safer, use the iterator or the .at() method to access the elements. Both these methods perform bounds checking and will not let you go beyond the last valid element