If you have a vector of anything sortable and comparable with less-than (<), this might be a solution:
#include <algorithm>
#include <vector>
using namespace std;
/*
* Find the element in haystack closest to needle.
* NOTE: haystack must be sorted
*/
template<typename T>
T find_closest (T needle, std::vector<T> haystack) {
/* handle special cases where needle
* is smaller than the first or bigger
* than the last element
*/
if (needle <= haystack.front()) {
return haystack.front();
}
if (needle >= haystack.back()) {
return haystack.back();
}
auto closest = adjacent_find(haystack.begin(), haystack.end(),
[&needle] (T i, T j) {return i =< needle && needle <= j;});
return (needle-(*closest) < *(closest+1)-needle) ? *closest : *(closest+1);
}
int main ()
{
int needle = 200;
std::vector<int> haystack = {55, 67, 458, 23, 81, 33, 782, 375, 528, 405, 324,
950, 46, 14, 864, 551, 38, 167, 518, 630};
sort(haystack.begin(), haystack.end());
int found = find_closest(needle, haystack);
}