c++ - 如何返回3个值之间的最大值?

标签 c++ algorithm max overloading initializer-list

我尝试使用 ma​​x 函数返回最大值,但它不适用于 3 个值。

代码块错误:

error: '__comp' cannot be used as a function

代码:

#include <iostream>
using namespace std;

int main()
{
    cout << max(5, 10, 20);
}

最佳答案

使用这个重载函数std::max接受 std::initializer_list<int> 类型的对象:

cout << max( { 5, 10, 20 } );

该函数有以下声明

template<class T>
constexpr T max(initializer_list<T> t);

否则编译器会尝试选择该函数

template<class T, class Compare>
constexpr const T& max(const T& a, const T& b, Compare comp);

并发出错误。

请注意,您需要包含 header <algorithm> ,

关于c++ - 如何返回3个值之间的最大值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61688371/

相关文章:

c++ - 构造函数主体前的冒号是否表示继承

python - 求和可被 M 整除的大小为 K 的子数组的数量?

r - 如何输出数据框中行范围内的最大值?

filter - Tableau - 度量最大值的过滤器维度

c++ - 在静态库中混合 C 和 C++ 代码

'-' 类上的 C++ 'Matrix' 运算符

c++ - 是否可以在其范围之外访问局部变量的内存?

javascript - 使用异或变量计算

algorithm - 自由移动的球体何时可以逃离由一组不可通过的坐标定义的 ‘cage’?

java - 如何在Java中返回二叉树中最频繁的元素