C++ Examples© 2024 TBD
Algorithms

max



#include <algorithm>
#include <iostream>
#include <initializer_list>
                                                                                                                
using std::initializer_list,
    std::max,
    std::cerr;
                                        
class Temp{
    public:
        int a, b;
        Temp(int i, int j):a(i), b(j){}
};

bool operator<(const Temp& l, const Temp& r)
{
    if((l.a + l.b) < (r.a + r.b)){
        return true;
    }
    return false;
}  


bool operator==(const Temp& l, const Temp& r)
{
    return l.a == r.a && l.b == r.b;
} 

typedef initializer_list<Temp> my_list;

int main(){
    Temp w(9,16), x(6, 18);
    auto print = [] (Temp t){
        cerr << "Temp(" << t.a << ", " << t.b << ")\n";
    };  


    Temp y = max(w, x);
    if(y == w){
        cerr << "first is greater\n" ;
    }else{
        cerr << "second is greater\n" ;
    }

    my_list l = {Temp(16, 256), Temp(4, 16), Temp(12, 144), Temp(4, 16), Temp(19, 361), Temp(9, 81), Temp(3, 9), Temp(15, 225), Temp(5, 25), Temp(6, 36), Temp(1, 1), Temp(8, 64), Temp(13, 169), Temp(0, 0), Temp(2, 4), Temp(2, 4), Temp(3, 9), Temp(10, 100), Temp(18, 324), Temp(14, 196), Temp(17, 289), Temp(7, 49), Temp(11, 121)};

    Temp t = max(l);
    print(t);

    auto test = [] (Temp a, Temp b)->bool{
        if((a.a + a.b) < (b.a + b.b)){
            return true;
        }
        return false;
    };

    y = max(w, x, test);
    if(y == w){
        cerr << "first is greater\n" ;
    }else{
        cerr << "second is greater\n" ;
    }


    t = max(l, test);
    print(t);

    return 0;
}      
© 2024 TBD