title: Avoiding if statement inside a for loop?
body: <p>I have a class called <code>Writer</code> that has a function <code>writeVector</code> like so:</p>
  
  <pre><code>void Drawer::writeVector(vector&lt;T&gt; vec, bool index=true)
  {
      for (unsigned int i = 0; i &lt; vec.size(); i++) {
          if (index) {
              cout &lt;&lt; i &lt;&lt; "\t";
          }
          cout &lt;&lt; vec[i] &lt;&lt; "\n";
      }
  }
  </code></pre>
  
  <p>I'm trying not to have a duplicate code, while still worrying about the performance.
  In the function, I'm doing the <code>if (index)</code> check on every round of my <code>for</code>-loop, even though the result is always the same.
  This is against "worrying about the performance".</p>
  
  <p>I could easily avoid this by placing the check outside of my <code>for</code>-loop.
  However, I'll get loads of duplicate code:</p>
  
  <pre><code>void Drawer::writeVector(...)
  {
      if (index) {
          for (...) {
              cout &lt;&lt; i &lt;&lt; "\t" &lt;&lt; vec[i] &lt;&lt; "\n";
          }
      }
      else {
          for (...) {
              cout &lt;&lt; vec[i] &lt;&lt; "\n";
          }
      }
  }
  </code></pre>
  
  <p>So these are both "bad" solutions for me.
  What I've been thinking, is two private functions, one of them outs the index and then calls the other.
  The other one only outs the value.
  However, I can't figure out how to use it with my program, I'd still need the <code>if</code> check to see which one to call...</p>
  
  <p>According to the problem, polymorphism seems like a correct solution.
  But I can't see how should I use it here.
  What would be the preferred way to solve this kind of problem?</p>
  
  <p>This is not a real program, <strong>I'm just interested in learning how this kind of problem should be solved.</strong></p>