Find largest and second largest element in a range

后端 未结 11 2009
情歌与酒
情歌与酒 2020-12-10 07:30

How do I find the above without removing the largest element and searching again? Is there a more efficient way to do this? It does not matter if the these elements are dupl

11条回答
  •  轮回少年
    2020-12-10 07:49

    nth_element(begin, begin+n,end,Compare) places the element that would be nth (where "first" is "0th") if the range [begin, end) were sorted at position begin+n and makes sure that everything from [begin,begin+n) would appear before the nth element in the sorted list. So the code you want is:

    nth_element(container.begin(),
                container.begin()+1,
                container.end(),
                appropriateCompare);
    

    This will work well in your case, since you're only looking for the two largest. Assuming your appropriateCompare sorts things from largest to smallest, the second largest element with be at position 1 and the largest will be at position 0.

提交回复
热议问题