Please see the following 2 examples:
#include <iostream>
#include <algorithm>
#include <vector>
int main()
{
int n;
std::cin>>n;
std::vector<int> V(n);
// some initialization here
int max = *max_element(&V[0], &V[0]+n);
}
This gives the following compiling error:
error C3861: 'max_element': identifier not found
But when I replace the call of *max_element(&V[0], &V[0]+n); to *max_element(V.begin(), V.end()); it does compile:
#include <iostream>
#include <algorithm>
#include <vector>
int main()
{
int n;
std::cin>>n;
std::vector<int> V(n);
// some initialization here
int max =*max_element(V.begin(), V.end());
}
Could somebody explain me why the two are different?
This is due to argument dependant lookup (aka ADL).
Since max_element is defined in the namespace ::std, you should really write std::max_element everywhere. But, when you use it in its second form
max_element(V.begin(), V.end());
since V.begin() and V.begin() have type defined itself in ::std, ADL kicks in and finds std::max_element.
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