skgbanga skgbanga - 1 month ago 8
C++ Question

STL algorithm for smallest max element than a given value

Recently I came across this code fragment:

// 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;
}
}


I was wondering if anyone can think of an elegant stl algorithm to replace the above. Essentially we have to go through all the elements, and also keep track of the one which we need. This is not similar to
std::max_element
(atleast I can't model it that way).

Answer
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;
  });

The trick is to write a comparison function that declares any "good" element (one that's greater than *given) to compare smaller than any "not good" element. Two "good" elements are compared normally; two "bad" elements are always declared equivalent.

Comments