|
|
|
|
|
by stabbles
2539 days ago
|
|
In C++ you typically access arrays with unsigned integers (size_t), and a common pitfall is: for (size_t i = v.size() - 1; i >= 0; --i) {
std::cout << i << ": " << v[i] << std::endl;
To fix the infinite loop you could write: for (size_t i = v.size(); i > 0; --i) {
std::cout << i - 1 << ": " << v[i - 1] << std::endl;
Neither is great. Switching to signed integers might make your compiler throw warnings at you.However, 1-based indexing does not work out well with modular arithmetic: # 1 based
v[1 + (i - 1) % v.size()]
# 0 based
v[i % v.size()]
There's pros and cons with both schemes. |
|
[1] https://docs.julialang.org/en/v1/base/math/#Base.mod1
[2] https://docs.julialang.org/en/v1/base/arrays/index.html#Base...