title: Using modulus operator to keep within indices of container
body: <p>Assume I have a vector v with m elements in it, and a random access index to the vector called i.</p>
  
  <p>When I increment the index, if it goes out of bounds, I want to index the first (zeroth) element. Similarly, when I decrement the index, if the index is &lt; 0, I want to index to last element. At the moment I'm only moving through the container one element at a time, so came up with this function:</p>
  
  <pre><code>unsigned int GetIndexModM(int index,unsigned int m) {return (index + m) % m;}
  </code></pre>
  
  <p>The call-site might look like this:</p>
  
  <pre><code>std::vector&lt;Whatever&gt; v = ... // initialise with 5 elements
  unsigned int i = 0;
  unsigned int j = GetIndexModM(static_cast&lt;int&gt;(i) - 1,v.size()); // get preceeding index
  </code></pre>
  
  <p>This function will fail however if one subtracts a value > m from index:</p>
  
  <pre><code>unsigned int j = GetIndexModM(static_cast&lt;int&gt;(i) - 17,v.size()); // oops: returns -2
  </code></pre>
  
  <p>My question: What's the most elegant implementation of a function that takes any integer and returns it's place as an index?</p>