0
int main()
{
vector<int> v={1,2,4};
int &a=*v.begin();
cout<<a;
    return 0;
}

In the above code segment, the dereferenced value of the iterator v.begin() assigned to &a. Printing a displays 1

int main()
{
vector<int> v={1,2,4};
int a=*v.begin();
cout<<a;
    return 0;
}

Here, the iterator is deferenced and the value is assigned to a (without the &) instead. Printing a still displays 1.

I'm still learning C++ and it doesn't make sense to me why the first code block works. What does int &a signify?

273K
  • 29,503
  • 10
  • 41
  • 64
Deb
  • 355
  • 2
  • 9
  • 4
    You seem to be asking what a _reference variable_ is. – Drew Dormann Aug 07 '22 at 18:52
  • 3
    References are a fundamental concept in C++. I don't want to discourage you from writing small programs to test things out, but when something is so fundamental as a reference, you really should be studying a book or tutorial. You aren't going to learn what they are by experimentation. (or by asking on Stack Overflow). – john Aug 07 '22 at 18:55
  • I'd also take issue with the notion that you are "assigning iterators" to anything. You dereference the iterator before you assign anything anywhere. – Nathan Pierson Aug 07 '22 at 18:56

1 Answers1

5

int& a = *v.begin(); makes a a reference to the first element in the vector so anything you do to that reference is reflected upon the referenced element. Example:

#include <vector>
#include <iostream>

int main() {
    std::vector<int> v = {1, 2, 4};
    int &a = *v.begin();
    a = 100;
    std::cout << v[0]; // prints 100
}

If you instead do int a = *v.begin(); you copy the value held by v[0] into a and v[0] and a live their separate lifes:

#include <vector>
#include <iostream>

int main() {
    std::vector<int> v = {1, 2, 4};
    int a = *v.begin();
    a = 100;
    std::cout << v[0]; // prints 1
}
Ted Lyngmo
  • 93,841
  • 5
  • 60
  • 108