std :: max_element编译错误,C++

Edu*_*yan 2 c++ algorithm lookup stl std

请参阅以下2个示例:

#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);
}
Run Code Online (Sandbox Code Playgroud)

这给出了以下编译错误:

错误C3861:'max_element':找不到标识符

但当我替换它的调用时*max_element(&V[0], &V[0]+n);, *max_element(V.begin(), V.end());它确实编译:

#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());
}
Run Code Online (Sandbox Code Playgroud)

有人可以解释一下为什么两者不同吗?

YSC*_*YSC 9

这是由于参数依赖查找(也称为ADL).

既然max_element在命名空间中定义了::std,那么你应该std::max_element到处写.但是,当你以第二种形式使用它时

max_element(V.begin(), V.end());
Run Code Online (Sandbox Code Playgroud)

既然V.begin()并且V.begin()有自己定义的类型::std,ADL就会启动并找到 std::max_element.