Quite frequently I need to extract the N (> 1) highest elements from an unsorted STL container. The naive way to do this is using <queue>.
Is there a quicker, less boilerplate way?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
std::partial_sortif you need them in order, otherwisestd::nth_element, usinggreateras your predicate in either case.I can’t tell if by extract you mean you want to remove, but if you do then another option is heapifying your container with
make_heapand then yanking theNelements out of it.