请看下面两个例子:
#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);
}
这给出了以下编译错误:
error C3861: 'max_element': identifier not found
但是当我将 *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());
}
谁能解释一下为什么两者不同?
最佳答案
这是由于 argument dependant lookup (又名 ADL)。
因为 max_element
是在命名空间 ::std
中定义的,所以你真的应该在所有地方都写上 std::max_element
。但是,当您以第二种形式使用它时
max_element(V.begin(), V.end());
因为 V.begin()
和 V.begin()
在 ::std
中定义了自己的类型,ADL 开始并且 < em>找到 std::max_element
。
关于c++ - std::max_element 编译错误,C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48823946/