Home > Net >  How do I pass a standalone template function to a standard algorithm as a BinaryOperation argument?
How do I pass a standalone template function to a standard algorithm as a BinaryOperation argument?

Time:10-16

I have an std::vector<int> v1 of size n, and I want to build an std::vector<int> v2 such as for every i from [0, n) v2[i] = max(v1[i], ..., v1[n-1]).

I wanna use a standard algorithm std::parial_sum for it, something like

std::partial_sum(v1.rbegin(), v1.rend(), v2.rbegin(), std::max);

The only problem is that it doesn't compile, as I get an couldn't deduce template parameter '_BinaryOperation' error for std::max.

Documentation for std::partial_sum suggests a concise syntax like

std::partial_sum(first, last, d_first, std::plus<>());

but std::plus is a class with an overloaded operator(), not a standalone function. What can I do to use std::max in a similar way?

CodePudding user response:

You cannot use a regular function as a callable object, because functions are not objects.

Either use a lambda:

std::partial_sum(v1.rbegin(), v1.rend(), v2.rbegin(), [](auto lhs, auto rhs) {
    return std::max(lhs, rhs);
});

Demo
Note that you can have that lambda as a separate variable too:

auto max = [](auto lhs, auto rhs) { return std::max(lhs, rhs); };
std::partial_sum(v1.rbegin(), v1.rend(), v2.rbegin(), max);

Or make your own callable object:

struct max {
    template<typename T>
    auto operator()(T const& lhs, T const& rhs) {
        return std::max(lhs, rhs);
    }
};
// [...]
std::partial_sum(v1.rbegin(), v1.rend(), v2.rbegin(), max{});

Demo

CodePudding user response:

You could define your own Max Struct comparator:

template<class T>
struct Mymax{
   T& operator()(const T& a, const T& b)
   {
      return (a < b) ? b : a;
   }
 };

`

  • Related