lundi 9 octobre 2017

Finding maximum and minimum in vector of custom data using algorithm

I have a data structure like this:

struct Speed {

       int set; //set by user
       int act; //actual speed
       int millis; //millis since epoch
}

vector<Speed> data;

Now I want to draw this vector. To create a nice axis, I want to find the max and min of data in this vector. I do like this but obviously, since it is based only on set, it will fail me if at any point act is smaller or larger than set. I mean the Y axis of the chart should be between minimum of set, act and maximum of set, act.

auto max = std::max_element(begin(data), end(data),
                            [&](const Speed& a, const Speed& b){
    return a.set() < b.set(); 
    //how about act?
});

auto min = std::min_element(begin(data), end(data),
                            [&](const Speed& a, const Speed& b){
    return a.set() < b.set();
    //how about act?
});

**I KNOW ** how to write a normal code not involving algorithm and lambdas to achieve the result...but I am interested to see how it is possible to do with algorithm/lambda WITHOUT having operator overloading in the structure.

I could also do the same for act then compare results...but that would cost me 4 loops!

Aucun commentaire:

Enregistrer un commentaire