0

I read everywhere that back() function return reference to the last element, but I have a doubt.

I created a vector with elements 1,3,5 resp.Then I wrote the following code

int i = v.back();
i++;

after the above two statements , I printed the vector and I got the output 1 3 5 whereas it should be 1 3 6 as I incremented the reference.

but when i do (v.back())++ and then print the values of the vector I get the result

1 3 6

I don't understand the difference in output , according to me it should be same. Please correct me if i am wrong.

Fred Foo
  • 355,277
  • 75
  • 744
  • 836
Raman Gupta
  • 169
  • 1
  • 1
  • 7

3 Answers3

8

The code does not increment the last element via a reference, it increments a copy of the last element. Change to:

int& i = v.back();
i++;
hmjd
  • 120,187
  • 20
  • 207
  • 252
  • okay maybe i am wrong but as said back() function returns a reference therefore i is a reference to the last element.so what's the need of &i. thanks – Raman Gupta Jul 06 '12 at 09:24
  • Yep, `back()` does return a reference but that does not make `i` a reference implicitly. You have to declare `i` as a reference otherwise it copies the object to which the return value of `back()` refers. – hmjd Jul 06 '12 at 09:27
  • @user1139048: back() returns a reference, but by `int i=v.back();` you just use the value behind this reference to initialise a local variable (which is independent from your vector). `int& i=v.back();` stores the reference itself, so you can change the vector element via i. – C. Stoll Jul 06 '12 at 09:29
0
int i = v.back();
i++;

This will increment i, not the value inside the vector. If you want to increment the last element of the vector, either do as you did (with (v.back())++) or use a reference:

int& i = v.back();
i++;
// v.back is now +1
Hampus Nilsson
  • 6,692
  • 1
  • 25
  • 29
0

According to this, back() returns reference. To alter your item assign it to reference or pointer, like so:

int& iref = v.back();
int* iptr = &v.back();

All further modification of these variables will cause changes in vector element.

aambrozkiewicz
  • 542
  • 3
  • 14