简体   繁体   中英

std::minmax initializer_list<T> argument

Maybe this question is a little bit theoretic , but I wonder what are the the design incentives behind defining std::minmax like this

template <class T>
pair<T,T> minmax (initializer_list<T> il);

Which means ,IMO, the passed object, li will be copied and each of its members must also be copy-constructible.

While, std::min_element (or for this matter std::max_element ) is more "efficient" in the sense only the container iterators are being passed (no need to actually copy the entire container)

template <class ForwardIterator>
ForwardIterator min_element (ForwardIterator first, ForwardIterator last);

EDIT - based on Joachim Pileborg comment, initializer_list<T> objects are not being copied, so I'm pinpointing my question - why std::minmax is constrained to such objects and not to arbitrary containers (which have "non-const" nature, so to speak)

For your updated question: minmax can also work with a general case of pair of iterators, it is called minmax_element . So minmax itself is just a convenience shorthand to be able to write compact things like this:

// define a, b, c here
int min, max;
std::tie(min, max) = std::minmax({a, b, c});

...instead of writing this:

// define a, b, c here
int min, max;
auto list = {a, b, c};
auto result = std::minmax_element(list.begin(), list.end());
min = *result.first;
max = *result.second;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM