Suppose I have an std::vector<int>:
std::vector<int> v;
[v is initialized]
and I want to get the maximum element of v. There is an algorithm for doing that:
int max_value = *std::max_element(v.begin(), v.end());
So far, so good.
Now, suppose that v contains 10,000,000 elements, and its 10th element is equal to std::numeric_limits<int>::max(). Is std::max_element() going to (unnecessarily) examine the 9,999,990 last elements of v, or is it going to recognize that there cannot be elements larger than std::numeric_limits<int>::max(), and thus stop after the 10th element?
I can't speak for all implementations, but libc++'s implementation of max_element does not do that.
There's a couple problems with the idea:
numeric_limits for the type of the elements of the sequence. (max_element works on anything that can be ordered.) This could be worked around with some template meta-programming.max_element that takes a comparison predicate, not just operator <. What's the max value in that case?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