Iterating with size_t 0 as a boundary condition
What's the "correct" way to write a decreasing loop with a size_t value and a boundary condition. Example incorrect implementation:
for (size_t elemNum = listSize-1; elemNum >= 0; --elemNum) { /* ... */ }
When it reaches zero it will wrap around to the max value rather than acting as a boundary condi开发者_如何学Ction. Iterating the loop in reverse is necessary. It seems like a problem that would have a defacto standard solution but I can't find what it is.
The most succinct approach is to use post-increment:
for (size_t i = listSize; i--;) ...
elemNum = listsize;
while (elemNum--) {
/* work with elemNum varying from `listsize - 1` down to `0` */
}
I don't know of a standard way, but this should work:
for (size_t elemNum = listSize-1; elemNum < listSize; --elemNum) { /* ... */ }
You could use two variables instead:
size_t count = 0;
for (size_t elemNum = listSize-1; count < listSize; ++count, --elemNum) { /* ... */ }
for (size_t counter = listSize; counter > 0; --counter) {
size_t index = counter-1;
/* ... use `index` as an index ... */
}
size_t elemNum = listSize;
while (elemNum > 0) {
--elemNum;
// Do your work here.
}
You could use this as the condition:
elemNum != (size_t)-1
Or you could count up, and do some math (which the compiler will probably optimise out anyway) for your index:
for (size_t i = 1; i <= listSize; i++) {size_t elemNum = listSize-i; /* */}
If you can guarantee the starting value isn’t too large, a simple answer is: use a signed type instead.
The standard C++ way would be to use a std::reverse_iterator
.
Somehow within the loop you are accessing element elemNum
of a list, say via list[elemNum]
, where list
models the RandomAccessIterator concept. Suppose that list_iterator_type
is the decltype of list
. Your loop using reverse iterators becomes:
std::reverse_iterator<list_iterator_type> it, end = std::reverse_iterator<list_iterator_type>(list);
for (it = std::reverse_iterator<list_iterator_type>(list + listSize); it != end; ++it) {
// `*it` is `list[elemNum]`
}
精彩评论