How to find the index of second largest element in an array collection?

后端 未结 3 635
攒了一身酷
攒了一身酷 2021-01-25 08:43

I have a function which calculates sum of money spent on each checkout on a counter, After calculation, i want to find the best two checkout counter, I am able to find the index

3条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-01-25 09:28

    If you can keep all the values in memory (i.e. if you have fewer than billions of checkouts), you can either use std::partial_sort to sort the two largest elements (but leave the rest unsorted), or you can use std::nth_element twice, once with 1 and once with 2. (In both cases, your predicate should be std::greater, I suppose.)

    If you need to process the values in a streaming fashion (i.e. with constant space), then you'll need to keep track of each order index separately, essentially similar to what you're attempting already. Boost.Accumulators may have some tools to simplify that task.

提交回复
热议问题