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
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.