【问题标题】:Selecting the maximum “n” values选择最大“n”值
【发布时间】:2012-07-22 20:34:02
【问题描述】:

如果我有以下情况:

#include <iostream>
#include <vector>
#include <algorithm>
#include <iterator>

    struct Features{ int F1, F2, F3, F4; };

    int criterionFunction(Features const& features) {
        return
            -2*features.F1*features.F2
            +3*features.F1
            +5*features.F2
            -2*features.F1*features.F2*features.F3
            +7*features.F3
            +4*features.F4
            -2*features.F1*features.F2*features.F3*features.F4; }

如何应用transform() 来查找前三个 最大值

谢谢。

【问题讨论】:

  • 为什么是transformnth_elementpartial_sort 似乎更合适。
  • 请更具体。这可能是一个线性优化问题,或者您可能只想从现有列表中选择一些元素。

标签: c++ algorithm vector


【解决方案1】:

这是一个使用nth_element 的示例,它具有更简单的特征对象和标准函数(以减少混乱):

#include <algorithm>
#include <vector>
#include <iterator>
#include <iostream>

typedef int Features;

int criterionFunction(Features features) {
  return features;
}

int main() {
  std::vector<Features> v { 0, 4, 2, 5, 4, 3, -2, 1 };
  std::nth_element(v.begin(), v.begin() + 3, v.end(),
                   [](Features a, Features b) {
                       return criterionFunction(a) > criterionFunction(b);
                   });
  std::copy(v.begin(), v.begin() + 3,
            std::ostream_iterator<Features>(std::cout, " "));
}

对于您的原始Features 对象,缓存/记忆criterionFunction 的结果以防止重复调用可能很有用。

注意nth_element不会对两个分区中的元素进行排序;如果您希望前三个元素按排序顺序排列,请改用partial_sort

【讨论】:

  • 请注意,nth_element 确实导致 3 个项目按顺序。部分排序可以做到这一点。
  • @sehe OP 没有要求订购它们 :) 不过我要添加备注。
【解决方案2】:

你不能。这不是std::transform 所做的。

transform 将单个函数应用于序列中的每个元素。它不选择特定元素。

【讨论】:

    【解决方案3】:

    您可以使用std::transformstd::multiset 和插入迭代器的组合。

    vector<Features> v;
    ...fill it up
    multiset<int> ms;
    transform(v.begin(), v.end(), inserter(ms, ms.begin()), criterionFunction);
    

    那么三个最大值就是最后三个元素。

    【讨论】:

      猜你喜欢
      • 2011-08-28
      • 1970-01-01
      • 2017-12-07
      • 1970-01-01
      • 2022-12-11
      • 2011-04-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多