How to return the max value between 3 values?

Viewed 217

I am trying to return the max value using the max function but its not working on 3 values.

CodeBlocks Error:

error: '__comp' cannot be used as a function

The Code:

#include <iostream>
using namespace std;

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

Use this overloaded function std::max that accepts an object of the type std::initializer_list<int>:

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

This function has the following declaration

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

Otherwise the compiler tries to select the function

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

and issues an error.

Pay attention to that you need to include the header <algorithm>,

Related