Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to return the max value between 3 values? [duplicate]

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);
}
like image 396
Arnold-Baba Avatar asked Dec 18 '22 13:12

Arnold-Baba


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>,

like image 178
Vlad from Moscow Avatar answered Jan 13 '23 03:01

Vlad from Moscow