Search code examples
c++stl-algorithm

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?


Solution

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