Problem and solution
Posted Apr 5, 2008 12:08 UTC (Sat) by
emk (subscriber, #1128)
In reply to:
Problem and solution by man_ls
Parent article:
What If I Don't Actually Like My Users?
It took me a second, too, because it's using a strange (incorrect) looping idiom. Here, size_t is an unsigned type, so it can never be negative. If i == 0, and you write --i, it wraps around to a huge positive value. To fix it, try:
while (i > 0) {
Thanks to the unsigned nature of size_t, it's surprisingly hard to loop backwards over STL vectors without tripping over this bug. You could choose to use reverse iterators, which are clunky but safer:
vector<MyThingy>::const_reverse_iterator iter = stuff.rbegin();
for (; iter != stuff.rend(); ++iter) {
/* do something with */ *iter;
}
Also, I have no idea why the original function returns i. Was there a break somewhere in the original loop? Without one, i would always equal 0 (assuming the loop terminated successfully).
(
Log in to post comments)