title: What is the correct for loop code that traverses the neighbors of a matrix element and checks bounds?
body: <p>I can't seem to figure out an elegant way to do this, but I know I have seen it in the past. I just don't know what to search for.</p>
  
  <p>I am given the row and column indices, <code>r</code> and <code>c</code> of a 2-D matrix. I want to be able to traverse the 4 neighbors. If the element is at a corner, it will only have 2 neighbors. If the element is at the boundary, but not a corner, it will have 3 neighbors. If it's interior it will have 4 neighbors.</p>
  
  <p>So I want to traverse <code>(r+1,c)</code>, <code>(r-1,c)</code>, <code>(r,c+1)</code>, <code>(r,c-1)</code> and perform the bounds check <code>r &gt;= 0 &amp;&amp; r &lt; num_rows</code> and <code>c &gt;= 0 &amp;&amp; c &lt; num_cols</code> simultaneously in a double nested for loop.</p>
  
  <p>The only thing I was able to come up with is this:</p>
  
  <pre><code>vector&lt;vector&lt;int&gt;&gt; adds{{0,1},{1,0},{-1,0},{0,-1}}
  
  for(int i = 0; i &lt; adds.size(); i++)
  {
    //do bounds checking with r + adds[i][0] and c + adds[i][1]
    //do something with matrix[r + adds[i][0]][c + adds[i][1]]
  
  }
  
  </code></pre>
  
  <p>The particularly elegant one I remember seeing did something with a max function and didn't use the <code>adds</code> array that I have. </p>