简体   繁体   中英

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?

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 .

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