Search code examples
c++c++11stl-algorithm

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!


Solution

  • Generally, I would recommend most readable code.

    Thus, it would be something like (assuming at least one item):

    auto set_minmax = std::minmax_element(begin(data), end(data),
        [&](const Speed& a, const Speed& b) { return a.set < b.set; });
    
    auto act_minmax = std::minmax_element(begin(data), end(data),
        [&](const Speed& a, const Speed& b) { return a.act < b.act; });
    
    auto min_act_set = std::min(*set_minmax.first, *act_minmax.first);
    auto max_act_set = std::max(*set_minmax.second, *act_minmax.second);
    

    However, if the data is really big or the logic is more complex, I would recommend to have an object that accumulate statistics and do some kind of loop over the data.