【发布时间】:2012-01-28 16:15:46
【问题描述】:
我需要一个函数,它接受一个向量(假定已排序)和一个值,并返回 [edit] 大于 小于或等于该数字的最接近的数字,最好使用来自 STL 的算法。我想出了一个使用 std::lower_bound() 的解决方案,但它看起来很笨拙和丑陋:
struct ClosestCmp {
bool operator()(const int & x, const int & y) { return x > y; }
};
// vec is assumed to be sorted
int closest(const std::vector<int> & vec, int value)
{
std::vector<int>::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 << closest(vec, 2) << "\n"; // Should ouput "2"
std::cout << closest(vec, 3) << "\n"; // Should ouput "2"
std::cout << closest(vec, 4) << "\n"; // Should ouput "4"
谁能提出一种更优雅的方法,也许使用 STL 算法而不需要比较函数或反向迭代器?我查看了 STL,但找不到比这更好的解决方案。
【问题讨论】:
-
2 不大于等于 3,我猜你想打印 4?
-
更正:我需要小于或等于该值的最接近的数字,而不是更大。我的错。