std::max_element 编译错误,C++
std::max_element compile error, C++
请看以下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);
}
这会产生以下编译错误:
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 启动并且 找到 std::max_element
.
请看以下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);
}
这会产生以下编译错误:
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 启动并且 找到 std::max_element
.