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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With