4 ms·
In modern C++ these loops could alternatively be written as: std::vector<int> myVec; for( auto it = myVec.begin(); it != myVec.end(); ++it ); or if you pr
by azoth_ 12y ago
In modern C++ these loops could alternatively be written as:
std::vector<int> myVec;
for( auto it = myVec.begin(); it != myVec.end(); ++it );
or if you prefer the external begin/end syntax:
for( auto it = std::begin(myVec); it != std::end(myVec); ++it );
or the most succinct (replace && by & if writing):
for( auto && item : myVec );
- jjoonathan 12y agoYes, and it's probably good to note that the issue has been fixed so as to not unduly scare away any newcomers to C++. Thanks for doing it for me :) Still, at the time the for(auto& item : vec) syntax was merely a talking point being tossed around C++0x meetings. And to this day the project I'm working on still hasn't officially dropped support for C++90 so I'm stuck with the old syntax anyway :/
- pbsd 12y ago> or the most succinct (replace && by & if writing): That is strictly not necessary. `auto&&` is what is now being called a universal reference: `item` resolves to `const int&` if `myVec` is const, and to `int&` if `myVec` is mutable. `auto&&` does the right thing in the majority of cases. In fact, the following extension [1] has been proposed for C++17 (and already implemented in recent clang builds): for( item : myVec ) { /* do stuff */ } which is meant to be a short-hand for for( auto&& item : myVec ) { /* do stuff */ } [1] http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2014/n3994.htm http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2014/n399...
- StephanTLavavej 12y agoBoth auto& and auto&& produce const T& for a const vector<T>, and T& for a modifiable vector<T>. The difference between them is subtle: auto&& handles Humanity's Eternal Nemesis, vector<bool>.
- pbsd 12y agoOops, you're right of course; I got reference collapsing rules confused with the regular binding rules. Proxy objects will only bind to auto const& or auto&&, though, since they're generally returned by value. I was surprised to see that this does not come up in std::bitset nor std::valarray, but only std::vector<bool>.