Why does this work:
#include <algorithm>
#include <iostream>
#include <vector>
int main() {
std::vector<int> nums = {3, 7, 5};
std::cout << *min_element(nums.begin(), nums.end()) << "\n";
}
But this doesn't:
#include <algorithm>
#include <iostream>
int main() {
int nums[] = {3, 7, 5};
std::cout << *min_element(nums, nums + 3) << "\n";
}
I've discovered that if I change the call to min_element
in the second example so it includes a namespace like std::min_element
, it works fine. What I don't understand is why this isn't necessary in the first example. Does the vector
somehow magically know where to find min_element
, and if so, why?
In the first example, ADL is employed and min_element
is found. In this example, the arguments to min_element
are iterators (nums.begin(), nums.end()
).
Argument-dependent lookup, also known as ADL, or Koenig lookup, is the set of rules for looking up the unqualified function names in function-call expressions, including implicit function calls to overloaded operators. These function names are looked up in the namespaces of their arguments in addition to the scopes and namespaces considered by the usual unqualified name lookup.
In the implementation you are using, the iterators begin()
and end()
of the vector
are implemented in such a way that this could be possible.
In the second example, this is not possible because the arguments to min_element
are just addresses of the array nums
. So you have to specifically use std::
so that the lookup will be qualified.
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