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.
source to share
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.
source to share
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.
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> >}β
source to share