Mystery of Vector??

Hello, I am new to C++. I am practicing the vector using pop_back.
By running the following code, I was expecting to get:
12345
3
3
1254
Because I thought that
(1) a[2] = a[last_pos] will store the value 5 from index 4 into index 2 and the value 3 from index 2 will now be placed into index 4. This hypothesis came from the fact that pop_back eliminated 3, which used to be in index 2. Therefore, I expected last_pos now to have a value of 3.
(2) Under the same logic, I expected a[4] to hold 3.

However, I received:
12345
4
5
1254

It seems that I have not understood how vector works yet. Why did I get this result?
If neither las_pos nor a[4] is 3, then how come pop_back eliminated the value 3?

Thank you so much in advance!!!!

int main()
{
int i;
vector<int> a;
a = {1, 2, 3, 4, 5};

for (i = 0; i < a.size(); i++)
cout << a[i];
cout << endl;

int last_pos = a.size() - 1;
a[2] = a[last_pos];

cout << last_pos << endl;
cout << a[4] << endl;
a.pop_back();

for (i = 0; i < a.size(); i++)
cout << a[i];
cout << endl << endl;

return 0;
}
When you do

a[2] = a[last_pos]

a[2] becomes 5, but a[last_pos] remain 5 as well. It doesn't swap.

a[4] is a[last_pos], so cout << a[4] will return 5.

Good luck!
Thank you for the quick response!
but in this case,

cout << last_pos gave me 4, instead of 5.
cout << a[4] gave me 5 though.

Also, if a[4], which is the last element, is 5, then why does pop_back eliminate 3?
It seems to make no sense that a[4] is 5 when a[2] is also 5 as well....

I am sorry, but I'm very confused ><
cout << last_pos
has nothing to do with the array! You're just displaying the integer last_pos, which has the value a.size()-1 (which is 4). So that's not displaying an array element, like you might think it does! Try cout << a[last_pos].


pop_back does not eliminate 3, look at this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
int main()
{
int i;
vector<int> a;
a = {1, 2, 3, 4, 5};

// Now, a = 12345

for (i = 0; i < a.size(); i++)
cout << a[i];
cout << endl;

int last_pos = a.size() - 1; 
a[2] = a[last_pos]; 

// Now, a = 12545

cout << last_pos << endl;
cout << a[4] << endl;
a.pop_back();

// Now, a = 1254

for (i = 0; i < a.size(); i++)
cout << a[i];
cout << endl << endl;

return 0;
}


Notice my comments after each array-changing operation :)

Remember that you can also debug your application. Just put breakpoints around each array operation, and you'll be able to see exactly what's going on after each call of your code.
OMG thank you sooooo much!!
You made it completely easy to understand this!!

Thank you for letting me know about break point too. I started enjoying learning C++, so I will use these features to improve my skill!
Topic archived. No new replies allowed.