Skip to content

Instantly share code, notes, and snippets.

@tenomoto
Created May 27, 2016 07:07
Show Gist options
  • Save tenomoto/79f5fb60783d24dcb8bf7910da4052c6 to your computer and use it in GitHub Desktop.
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++
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);
}
@tenomoto
Copy link
Author

Use .cbegin() and .cend() for a vector, pointer arithmetic for a C-style array and std::begin() and std::end() for valarray.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment