What is the difference between an iterator with and without a reference character. (C ++ loop)

What is the difference between an iterator with and without a character and a character, as seen in cases 1 and 2 in the 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;
    }
}

      

It has something to do with creating an iterator object, and then what is available in the code block? I am very new to iterators.

+3


source to share


3 answers


The difference is that the first loop won't compile. :)

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

      



Created a temporary object returned by a member function begin

and bound to it using a non-const reference.

+4


source


This does not apply to iterators, but to how the keyword works auto

.

This syntax

auto const &i = (something)

      

will create a link to the object on the right side of the task; in this case a const reference to a temporary object which would be equivalent to

std::vector<int>::iterator const &i = (something)

      

Note that it auto &i = v.begin()

is invalid in this case , as it std::vector::begin()

does not actually return a link.



On the other hand, the unreferenced syntax

auto i = (something)

      

Creates an instance of an object that will be equivalent to

std::vector<int>::iterator i = (something)

      

In practice, these two statements are equivalent, since the reference is actually a lifelong extension of the referenced object. If the function begin()

returned a link, the unreferenced syntax will create a copy.

+2


source


You should use the second and not the first, because the first doesn't compile. begin

returns a temporary object by value and it is not allowed to bind a temporary object to a non-const reference. If so, then this is some extension provided by your compiler.

http://ideone.com/oBvFOu3

error: invalid initialization of non-const reference of type β€˜__gnu_cxx::__normal_iterator<int*, std::vector<int> >&’ from an rvalue of type β€˜std::vector<int>::iterator {aka __gnu_cxx::__normal_iterator<int*, std::vector<int> >}’

-1


source







All Articles