Selecting the maximum “n” values

前端 未结 3 1121
挽巷
挽巷 2021-01-25 16:43

If I have the following:

#include 
#include 
#include 
#include 

    struct Features{ int F1, F2,         


        
相关标签:
3条回答
  • 2021-01-25 17:07

    With a combination of std::transform, std::multiset, and an insert iterator you could.

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

    Then the three max values are the last three elements.

    0 讨论(0)
  • 2021-01-25 17:12

    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, " "));
    }
    

    For your original Features object, it might be useful to cache/memoize the results of the criterionFunction to prevent duplicate calls.

    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.

    0 讨论(0)
  • 2021-01-25 17:18

    You can't. It's not what std::transform does.

    transform applies a single function to every element in the sequence. It does not select specific elements.

    0 讨论(0)
提交回复
热议问题