hello,
I have a little experience with C, and I am trying to learn C++ (brave new world for me!). I have what I am sure is a most basic question. However, I am baffled...
Say I have the following code
Code:
std::vector<int> intArray;
for ( i = 0; i<=10; i++ )
{
intArray.push_back(2*i);
printf("%d %d %d\n",i, intArray.size(), intArray[i]);
}
printf("***********\n");
for ( i = 0; i<=5; i++ )
{
intArray.pop_back();
printf("%d %d\n",i, intArray.size());
}
this outputs what I expected after reading the vector tutorial
Code:
0 1 0
1 2 2
2 3 4
3 4 6
4 5 8
5 6 10
6 7 12
7 8 14
8 9 16
9 10 18
10 11 20
***********
0 10
1 9
2 8
3 7
4 6
5 5
Now, the tutorial I am reading (codeguru) says "...pop_back() removes the last element in the controlled sequence. The removed element becomes invalid, and size() is decremented". I am having a problem seeing the "becomes invalid" part.
To be explicit, can anyone tell me why the next code does not seg fault then when I add it immediately after the pop_back loop?
Code:
for ( i = 0; i<=10; i++ )
{
printf("%d %d %d\n",i, intArray.size(), intArray[i]);
}
I get
Code:
0 5 0
1 5 2
2 5 4
3 5 6
4 5 8
5 5 10
6 5 12
7 5 14
8 5 16
9 5 18
10 5 20
Thank you very much.
mc61