【问题标题】:transform_reduce with max_element带 max_element 的 transform_reduce
【发布时间】:2017-12-21 01:16:28
【问题描述】:

我正在尝试使用 transform_reduce 转换一组数字,然后将其减少到这些元素的最大值。

auto lambda = [](uint64_t x) {
     return function(x);
 };

 counting_iterator<uint64_t> start(1);
 counting_iterator<uint64_t> finish(bound);


 auto max_val = *transform_reduce(start, finish, lambda, std::max_element(start, finish));

我的逻辑是它将所有值从 1 更改为绑定到函数(1)到函数(绑定),然后使用这些值,给我最大的值,但是我遇到了问题,谁能帮我解决想要我想要达到的目标吗?

【问题讨论】:

  • but I am having issues 描述您的问题。

标签: c++ algorithm transform reduce


【解决方案1】:

std::transform_reduce 的签名(取一个范围)是:

template<class InputIt, class T, class BinaryOp, class UnaryOp>
T transform_reduce(InputIt first, InputIt last,
               T init, BinaryOp binop, UnaryOp unary_op);

所以,在你的情况下:

auto max_val =
    std::transform_reduce(start, finish,
                          lambda(*start),
                          [](const auto& lhs, const auto& rhs){ return std::max(lhs, rhs); },
                          lambda);

如果合法(但不合法),[](const auto&amp; lhs, const auto&amp; rhs){ return std::max(lhs, rhs); } 可以替换为 using lambda_t = decltype(lambda(*start)); static_cast&lt;const lambda_t &amp; (*)(const lambda_t&amp;, const lambda_t&amp;)&gt;(&amp;std::max&lt;lambda_t&gt;) 因为std::max&lt;T&gt; 会模棱两可(可能是max(const T&amp;, const T&amp;)max(std::initializer_list&lt;T&gt;)),所以额外的演员表。

但无论如何,我们不允许获取大多数std函数的地址,包括std::max

【讨论】:

  • 你确定最后一段吗?你用的是哪个编译器?
  • @Nikolai:我一般使用 coliru 或 godbold,但他们不支持 std::transform_reduce :((甚至是 cppreference 示例)...
  • 最后一段中建议的替换是不合法的,因为即使指定了模板参数,std::max 仍然模棱两可。见stackoverflow.com/questions/47625376/…
  • @RyanCu:澄清了获取std::max的地址是非法的,即使选择右重载(以及选择右重载的方式)也是如此。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-07-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-08-09
相关资源
最近更新 更多