选择最大的“N”值 [英] Selecting the maximum “n” values
本文介绍了选择最大的“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; }
如何申请变换()
找到第一个三 最大值的?
感谢。
推荐答案
下面是一个使用例子 nth_element
用一个简单的功能,对象和标准功能(以减少混乱):
Here is an example using nth_element
with a simpler feature object and criterion function (to reduce clutter):
#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, " "));
}
有关原始的功能
对象时,它可能是有用的缓存/的 criterionFunction
的结果memoize的,以prevent重复呼叫。
For your original Features
object, it might be useful to cache/memoize the results of the criterionFunction
to prevent duplicate calls.
注意 nth_element
不会在两个分区中的元素进行排序;如果你想在有序前三个元素,使用 partial_sort
代替。
Note that nth_element
does not sort the elements in the two partitions; if you want the first three elements in sorted order, use partial_sort
instead.
这篇关于选择最大的“N”值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文