我尝试使用 max 函数返回最大值,但它不适用于 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/