mardi 3 mars 2020

Comparing Different Properties of a Class in a std::vector of a Class

I really didn't know what's the proper title for this would be, please bear with me.

So, imagine I have a class like:

class data {
    double a;
    double b;
    double c;

    bool is_blue;
};

and then I use it to construct a vector, std::vector<data> vdata. What I’m interested in is to be able to compare values of the vector based on the given property of the class. For instance, I’d like to find the element with smallest a, or find all elements with b > 2.0, or is_blue == true.

I have a few ideas on how to achieve this, but they don’t cover all the cases that I want to. For instance, I can probably loop over elements of the vdata, select a’s and construct a std::vector<double> and then use std::min_element to get the min. Or, use std::find to find what I want.

Or, maybe I can use std::transform and a lambda and generate a vector indicating if my test passed or not, and then select from that, like:

std::vector<bool> s;
std::transform(s.begin(), s.end(), std::back_inserter(ordinals),
                   [](auto &d) -> bool { return d.b > 2.0 });

I also thought maybe I can use std::sort and basically sort my vdata based on what I’m interested in. I’m not even sure if this method make sense.

So, I know how to approach this in different ways, and they work but I feel I'm missing something, and it should be a better way that covers all the cases. I'm mostly interested in some comparisons and min/max elements. I also have a complete control over the data class, so, I can freely add to it, encapsulate it into another class, etc.

P.S. Please let me know if I can choose a better title for this question.

Aucun commentaire:

Enregistrer un commentaire