2012-07-22 114 views
1

如果我有以下几点:选择最大的“n”值

#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()找到第一最大值

谢谢。

+1

为什么要变换? 'nth_element'或'partial_sort'似乎更合适。 – Philipp 2012-07-22 20:36:07

+1

请更具体。这可能是一个线性优化问题,或者您只想从现有列表中选择一些元素。 – Philipp 2012-07-22 20:37:11

回答

1

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

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

1

结合使用std::transform,std::multiset和插入迭代器,您可以。

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

然后三个最大值是最后三个元素。

2

下面是使用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对象,它可能是有用的缓存/ memoize的该criterionFunction结果以防止重复呼叫。

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

+0

请注意''nth_element'不会导致3个项目_in order_。部分排序会做到这一点。 – sehe 2012-07-22 21:23:18

+0

@sehe OP没有要求他们订购:) 虽然我正在添加一个评论。 – Philipp 2012-07-22 21:31:28