Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why need std::minmax_element?

Why do we need a combo version of std::min_element and std::max_element for std::minmax_element? Is it just for saving comparisons, or other benefits behind it?

like image 561
Chen OT Avatar asked Dec 11 '22 19:12

Chen OT


2 Answers

std::min_element and std::max_element need to traverse the entire container before they return. If you use std::min_element followed by std::max_element then that's two traversals, whereas if you use std::minmax_element then you only need one.

So yes, it's "just" for saving comparisons, but I think halving the amount of work you need to do to retrieve needed data with no loss of clarity is very worthwhile.

like image 123
TartanLlama Avatar answered Dec 13 '22 08:12

TartanLlama


Check a reference page.

It lists the two differences :

This algorithm is different from std::make_pair(std::min_element(), std::max_element()), not only in efficiency, but also in that this algorithm finds the last biggest element while std::max_element finds the first biggest element.

The mentioned efficiency gain, is because std::minmax_element only requires to process the data once, whereas running both std::min_element and std::max_element would require processing the data twice.

like image 28
Sander De Dycker Avatar answered Dec 13 '22 10:12

Sander De Dycker