Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

std::max_element compile error, C++

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?

like image 710
Eduard Rostomyan Avatar asked Jul 19 '26 13:07

Eduard Rostomyan


1 Answers

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.

like image 172
YSC Avatar answered Jul 22 '26 03:07

YSC



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!