3

Wikipedia tells me that

Reference is a simple reference datatype that is less powerful but safer than the pointer type inherited from C

I am learning C++ and I came across the function vector::front().

In the documentation it says the fuction

Returns a reference to the first element in the vector.

However, as shown in the code below, the return value is treated as not the reference but the element itself.

vector<int> my_vector(1); // initialising a vector
my_vector.push_back(10); // inserting 10
int number = my_vector.front() + 1; // number = 11

If my_vector.front() is a reference to the first element, shouldn't it be dereferenced with (*) in order to access the value?

Seeing that

*my_vector.begin() == my_vector.front() == 10

and I can do arithmetics to the iterator, should I think of iterators as something similar to pointers in C, and think of reference as a value?

Min Kweon
  • 33
  • 4
  • Also, this answers your question about iterators vs pointers: [How are iterators and pointers related?](http://stackoverflow.com/q/2728190/3425536) – Emil Laine Feb 14 '16 at 13:46

3 Answers3

3

... should I think of iterators as something similar to pointers in C, and think of reference as a value?

Yes, iterators implement pointer like behavior.

Think of references as alias for a specific value stored.

πάντα ῥεῖ
  • 1
  • 13
  • 116
  • 190
2

my_vector.front() returns, as you already stated, a reference to the first element, not an iterator/pointer. References do not need to be dereferenced in order for their values to be used.

and I can do arithmetics to the iterator, should I think of iterators as something similar to pointers in C, and think of reference as a value?

Exactly. Iterators are basically glorified pointers used for container access while references are more or less *pointer (dereferenced pointers).

Hatted Rooster
  • 35,759
  • 6
  • 62
  • 122
2

When an object is passed or returned by reference, using this reference is like using the original object itself (including modifying it !). Try for example:

...
my_vector.front() = number *2; 
cout << number<<" "<<  my_vector.front() <<endl;   

Iterators are pointer like. You have to dereference them (with * or ->) to access to the object it refers to. The arithmetic possibilities depend however strongly on the kind of iterator and might be much more limited than for pointers:

my_vector.begin()+10    // ok for a random access iterator on vectors, not for 
                        // bidirectional iterators on iterators on a list 
Christophe
  • 68,716
  • 7
  • 72
  • 138