Use vector <int> :: iterator by reference, but with an error
#include<vector> #include<iostream> using namespace std; int main() { vector<int> vec = {1,2,3,4}; for(auto & it = vec.begin(); it != vec.end(); ++it) { cout << *it << endl; } } Hi everyone, in C ++ I use an iterator by reference such as "auto and it" and the compiler returns an error
": invalid initialization of a non-constant link of type '__gnu_cxx :: __ normal_iterator> &' from an rvalue of type 'std :: vector :: iterator {aka __gnu_cxx :: __ normal_iterator>}' for (auto and it = vec.begin (); it ! = vec.end (); ++ it) ".
I know that "auto it = vec.begin ()" works fine, but as we all know, passing by reference will improve efficiency in C ++, so why does this error happen when I use "auto and it"?
so why does this error occur when I use "auto and it"?
See the return type begin . It does not return the link. It returns an iterator by value. Therefore, the return value is temporary in the rvalue category. Time series (rvalues) cannot be tied to non-constant references. This is what the error means "incorrect initialization of a non-constant type reference ... from an rvalue type ...".
In addition, changing the begin pointer in the container will make little sense. It would be foolish for begin return a link.
Decision. Just make a copy of the iterator by declaring a non-reference value, as you know, works great.
but, as we all know, passing by reference will improve efficiency in C ++
This is nonsense. A rolling link is unlikely to improve performance. Also, you are not trying to submit the link here. You are trying to bind a link to the object returned by a function.
Almost, if not always, iterators copy very quickly ( std::vector::iterator course), and the indirectness that you can represent with a link may be less effective.
std::vector::begin returns an rvalue (temporary object). You cannot reference a temporary object using auto& (reference to a non-constant lvalue). If you want to take the specified return value by reference, you can use auto&& instead of auto& , but I do not recommend it.
Using auto&& will create a mutable rvalue reference for the return value of std::vector::begin . This will extend the life , but I recommend using only auto .
Using rvalue links will not improve the efficiency of your code, the compiler will optimize copying / moving the mediation returned from std::vector::begin by value.
auto keyword gets the type as a temporary object from the expression (std :: vector :: begin) because it is a temporary object and, therefore, the compiler cannot output a link to it. Auto & (non-const lvalue)
The best approach in your case for use without auto var reference instead of auto & var
If you are trying to use Reference, C ++ 11 introduced rvalue-reference, which can bind to temporarily changing the object in && & instead of and below
vector<int> vec = {1,2,3,4}; for(auto && it = vec.begin(); it != vec.end(); ++it) { cout << *it << endl; }