title: Elegant way to find closest value in a vector from above
body: <p>I need a function that takes a vector (assumed to be sorted), and a value, and returns the closest number that's [edit] <strike>greater than</strike> less than or equal to that number, preferably using an algorithm from the STL. I have come up with a solution using std::lower_bound(), but it seems kludgy and ugly:</p>
  
  <pre><code>struct ClosestCmp {
      bool operator()(const int &amp; x, const int &amp; y) { return x &gt; y; }
  };
  
  // vec is assumed to be sorted
  int closest(const std::vector&lt;int&gt; &amp; vec, int value)
  {
      std::vector&lt;int&gt;::const_reverse_iterator cri =
          std::lower_bound(vec.rbegin(), vec.rend(), value, ClosestCmp());
      if (cri != vec.rend()) {
          return *cri;
      }
      return -1;
  }
  
  // ...
  vec.push_back(1);
  vec.push_back(2);
  vec.push_back(4);
  vec.push_back(5);
  std::cout &lt;&lt; closest(vec, 2) &lt;&lt; "\n"; // Should ouput "2"
  std::cout &lt;&lt; closest(vec, 3) &lt;&lt; "\n"; // Should ouput "2"
  std::cout &lt;&lt; closest(vec, 4) &lt;&lt; "\n"; // Should ouput "4"
  </code></pre>
  
  <p>Can anyone suggest a way that's more elegant, maybe using an STL algorithm without needing a comparison function or a reverse iterator? I have looked in the STL, but haven't been able to find a better solution than this.</p>