# The first number less than or equal to a needle

How do you find the first number less than or equal to a needle in an STL container? The following code does this and provides tests to ensure things are working as expected. Although the code is written for a vector, it could be adapted to any container providing a `ForwardIterator`.

```#include &lt;algorithm&gt;
#include &lt;vector&gt;
#include &lt;iostream&gt;

//Find the largest number less than or equal to a needle number
double FindLargestLessThanEqualNeedle(const std::vector&lt;double&gt; &amp;v, double needle){
auto up = std::upper_bound(v.begin(), v.end(), needle);
if(up==v.begin())
return v.front();
else if(up==v.end())
return v.back();
else
return *(up-1);
}

//Find the index of the largest number less than or equal to a needle number
size_t FindLargestLessThanEqualNeedleIdx(const std::vector&lt;double&gt; &amp;v, double needle){
auto up = std::upper_bound(v.begin(), v.end(), needle);
if(up==v.begin())
return 0;
else if(up==v.end())
return v.size()-1;
else
return up-v.begin()-1;
}

int main(){
std::vector&lt;double&gt; v={{0,1,4,8,10,15,20}};
std::cout&lt;&lt;FindLargestLessThanEqualNeedle(v,-1)&lt;&lt;std::endl;
std::cout&lt;&lt;FindLargestLessThanEqualNeedle(v,25)&lt;&lt;std::endl;
std::cout&lt;&lt;FindLargestLessThanEqualNeedle(v,8)&lt;&lt;std::endl;
std::cout&lt;&lt;FindLargestLessThanEqualNeedle(v,9)&lt;&lt;std::endl;
std::cout&lt;&lt;FindLargestLessThanEqualNeedle(v,10)&lt;&lt;std::endl;

std::cout&lt;&lt;FindLargestLessThanEqualNeedleIdx(v,-1)&lt;&lt;std::endl;
std::cout&lt;&lt;FindLargestLessThanEqualNeedleIdx(v,25)&lt;&lt;std::endl;
std::cout&lt;&lt;FindLargestLessThanEqualNeedleIdx(v,8)&lt;&lt;std::endl;
std::cout&lt;&lt;FindLargestLessThanEqualNeedleIdx(v,9)&lt;&lt;std::endl;
std::cout&lt;&lt;FindLargestLessThanEqualNeedleIdx(v,10)&lt;&lt;std::endl;
}
```