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?
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.
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 whilestd::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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With