Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between iterator with reference symbol, and without. (C++ loop)

Tags:

c++

iterator

auto

What is the difference between an iterator with the & symbol, and one without it, as seen in cases 1 and 2 in the contrived example below?

When should I use one or the other?

#include <iostream>
#include <vector>
int main() {
    std::vector<int> v;
    v.push_back(1);
    v.push_back(2);

    // case 1:
    for (auto & i = v.begin(); i != v.end(); ++i) {
        std::cout << *i << std::endl;
    }

    // case 2:
    for (auto i = v.begin(); i != v.end(); ++i) {
        std::cout << *i << std::endl;
    }
}

Is it something to do with the creation of an iterator object, and what is then available in the code block? I'm very new to iterators.

like image 806
windenergy Avatar asked Feb 21 '26 18:02

windenergy


1 Answers

The difference is that the first loop will not be compiled.:)

for (auto & i = v.begin(); i != v.end(); ++i) {
    std::cout << *i << std::endl;
}

You created a temporary object returned by member function begin and binded it with non-const reference.

like image 104
Vlad from Moscow Avatar answered Feb 23 '26 09:02

Vlad from Moscow



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!