4 ms·
Well, in my case, from time to time I have to do these stuff: for (int i = x.size() - 1; i >= 0; i--) ... for (int i = 0; i < x.size() - 1; i++) if (x[
by yongjik 12y ago
Well, in my case, from time to time I have to do these stuff:
for (int i = x.size() - 1; i >= 0; i--) ...
for (int i = 0; i < x.size() - 1; i++) if (x[i] < x[i+1]) ...
Both will blow up badly with unsigned ints.
(Well, to be fair, both will blow up with signed ints if x.size() is greater than 2G, so it's a matter of expectations.)
- Aldo_MX 12y agofor( size_t i = x.size(); i-- > 0; ) ...
- delinka 12y agoNow i is no longer an index, it's index-plus-one.
- Aldo_MX 12y agoNope, it's still an index, after the comparison and before executing the code inside the loop, i is decreased by 1. Remember that a for loop does something like this behind the scenes: size_t i = x.size(); while( i-- > 0 ) { // your code which needs backwards iteration here ; // do nothing because there is no third statement }
- shdon 12y agoNo, it's not. The check is done before the loop, so i has the correct value inside the loop. Still, the trick makes it look suspect and that's an argument against using it.
- Aldo_MX 12y ago> Still, the trick makes it look suspect and that's an argument against using it. This is true. The code is confusing to people not used to it. A workaround could be to hide this code inside a macro, so people not interested in digging into the code would take the macro's word: #define REVERSE_LOOP( x, i ) for( size_t i = x.size(); i-- > 0; ) But unfortunately, that doesn't help with the fear that people has against unsigned types.
- stinos 12y agoI have to do these stuff: for (int i = x.size() - 1; i >= 0; i--) . That yields compiler warnings for signed vs unsigned then, no?
- detrino 12y agoForget about for statements for a second and let's write both a counting up and a counting down loop using while statements. // count up std::size_t i = 0; while (i != 10) { std::cout << i << "\n"; ++i; } // count down std::size_t i = 10; while (i != 0) { --i; std::cout << i << "\n"; } After initialization a for statement repeats "test; body; advance", this is ideal for counting up loops, but what we need for counting down loops is "test; advance; body". Since C/C++ do not provide the latter as a primitive you have to use a while loop as shown above. Using a signed integer to shoehorn a counting down loop into a for statement at the cost of 1/2 your range is a hack IMO. Note that when working with iterators you have to resort to a while statement as iterating past begin is UB.