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;
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....
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].
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.