Selecting the maximum “n” values

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

If I have the following:

#include 
#include 
#include 
#include 

    struct Features{ int F1, F2,         


        
3条回答
  •  遇见更好的自我
    2021-01-25 17:12

    Here is an example using nth_element with a simpler feature object and criterion function (to reduce clutter):

    #include 
    #include 
    #include 
    #include 
    
    typedef int Features;
    
    int criterionFunction(Features features) {
      return features;
    }
    
    int main() {
      std::vector 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(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.

提交回复
热议问题