title: c++ minimum value of vector greater than another value
body: <p>I have a <code>vector</code> of <code>double</code>s. I wish to find both:</p>
  
  <ul>
  <li>The minimum value in the vector that is greater than (or equal to) a value <code>x</code>.</li>
  <li>The maximum value in the vector that is less than (or equal to) a value <code>x</code>.</li>
  </ul>
  
  <p>E.g. If I have a vector:</p>
  
  <pre><code>std::vector&lt;double&gt; vec = {0, 1.0, 3.0, 4.0, 5.0};
  </code></pre>
  
  <p>and a value</p>
  
  <pre><code>x = 2.6;
  </code></pre>
  
  <p>I wish to find <code>1.0</code> and <code>3.0</code>.</p>
  
  <p>What is the most efficient way of doing this?</p>
  
  <p>I have something like:</p>
  
  <pre><code>double x1, x2; // But these need to be initialised!!!
  double x = 2.6;
  for (i = 0; i &lt; vec.size(); ++i)
  {
    if (vec[i] &gt;= x &amp;&amp; vec[i] &lt; x2)
         x2 = vec[i];
    if (vec[i] &lt;= x &amp;&amp; vec[i] &gt; x1)
         x1 = vec[i];
  }
  </code></pre>
  
  <p>But how can I initialise x1 and x2? I could make x2 the maximum of the vector and x1 the minimum, but this requires an initial pass through the data. Is there any way to do this more efficiently?</p>
  
  <p>EDIT:</p>
  
  <p>A couple of assumptions I think I can/cannot make about the data:</p>
  
  <ul>
  <li>There are no negatives (i.e. the minimum possible number would be <code>0</code>)</li>
  <li>It is not necessarily sorted. </li>
  </ul>