5 ms·
With reasonable typedefs the first loop becomes: for(my_vector_t::const_iterator it = v.cbegin(), end = v.cend(); it != end; ) { ... } and if that looks long,
by fpoling 8y ago
With reasonable typedefs the first loop becomes:
for(my_vector_t::const_iterator it = v.cbegin(), end = v.cend(); it != end; ) {
...
}
and if that looks long, then the problem is poor choice of type names in STL. I.e if the const_iterator would be citer, then with
for(my_vector_t::citer it = v.cbegin(), end = v.cend(); it != end; ) {
...
}
the need for auto is greatly reduced. Besides, if one just uses indexes, the loop becomes:
for(sized_t i = 0; i != v.size(); ) {
if (v[i].second > 1 && i % rand() == 0) {
v.erase(v.begin() + i);
else
++i;
}
that does not have dangling reference bug from the original loop, easier to follow and with sane compiler one gets the same code.
Surely the code only works with vectors, but when one deals with vector of pairs, it implies very specific problem that rather unlikely to change. It also show that the need for auto really comes from the design of STL that leads to very long types that auto mitigates.
- jcelerier 8y ago> Surely the code only works with vectors, but when one deals with vector of pairs, it implies very specific problem that rather unlikely to change. maybe, maybe not. I often have much deeper changes than this. > It also show that the need for auto really comes from the design of STL that leads to very long types that auto mitigates. the same problem exists with int32_t or uint32_t or even int or char. The point is, using auto makes your code much more resilient to changes and much less likely to introduce bugs or performance losses due to unwanted conversions.
- AstralStorm 8y agoIn fact, in templated code decltype(v)::const_iterator might be preferable to plain auto in some cases as it forces a type that does have one of these...