Created
May 27, 2016 07:07
-
-
Save tenomoto/79f5fb60783d24dcb8bf7910da4052c6 to your computer and use it in GitHub Desktop.
Get value for a negative index or for an index larger than the size of container in C++
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
template <typename Iter> | |
Iter cyclic(Iter begin, Iter end, int i) | |
{ | |
auto n = std::distance(begin, end); | |
while (i < 0) i += n; | |
return begin + (i % n); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Use .cbegin() and .cend() for a vector, pointer arithmetic for a C-style array and std::begin() and std::end() for valarray.