Chen OT
Chen OT

Reputation: 3614

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?

Upvotes: 4

Views: 290

Answers (2)

TartanLlama
TartanLlama

Reputation: 65620

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.

Upvotes: 10

Sander De Dycker
Sander De Dycker

Reputation: 16243

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.

Upvotes: 3

Related Questions