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

标签 c++ algorithm stl std lookup

请看下面两个例子:

#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/

相关文章:

c++ - 命令行参数 c++

c++ - 使用 Swap 函数对类对象数组进行排序后出现重复条目​​ - C++

c++ - 切换案例的替代方案?

python - 以最快的方式生成所有 base 26 三元组

javascript - Tic-Tac_Toe 计算机算法

c++ - 如何删除 C++ 映射中的键值对?

java - 我需要修改这些哈希函数,以便它给出 0<x<10^9 范围内的值

带有自定义比较器的 C++ std::find

c++ - 用于存储顶点属性的数据结构

c++ - 为什么我可以将 std::map 的键传递给需要非常量的函数?