最近我遇到了这段代码片段:
// look for element which is the smallest max element from
// a given iterator
int diff = std::numeric_limits<int>::max();
auto it = nums.rbegin();
auto the_one = nums.rbegin();
for (; it != given; ++it) // this terminates
{
int local_diff = *it - *given;
// if the element is less than/equal to given we are not interested
if (local_diff <= 0)
continue;
if (local_diff < diff)
{
// this update the global diff
diff = local_diff;
the_one = it;
}
}
我想知道是否有人可以想到一个优雅的stl算法来取代上面的。基本上我们必须经历所有元素,并跟踪我们需要的元素。这与std::max_element
不相似(至少我不能那样建模)。
答案 0 :(得分:1)
auto the_one = std::min_element(nums.rbegin(), given,
[given](int a, int b) {
bool good_a = a > *given;
bool good_b = b > *given;
return (good_a && good_b) ? a < b : good_a;
});
诀窍是编写一个比较函数,声明任何&#34; good&#34;元素(一个大于*given
的元素)要小于任何&#34;不好的&#34;元件。两个&#34;好&#34;元素通常比较;两个&#34;坏&#34;元素总是声明等价。