Elchapo Elchapo - 1 month ago 4
C++ Question

Sort function for array of structures

I have a structure called rain. It is defines like this

struct Rain{
string month;
string year;
double rainfall;
}


I have an array of these (rain [240]) and I would like to sort using the sort algorithm. This is what I tried:

sort(rain.rainfall, rain.rainfall + 240);


but I get:

member reference base type 'Rainfall_data [240]' is not a structure or union
sort(rain.rainfall, rain.rainfall + 240);
~~~~^~~~~~~~~


I am just wondering if it is possible to use the sort algorithm this way, and if so what have I done wrong that it is not working?

Thank you for your help.

Answer

Often it's most convenient to embed the function into the class/struct:

struct Rain {
    string month;
    string year;
    double rainfall;
    bool operator < (const Rain& r1) const {
        return (rainfall < r1.rainfall);
    }
};

Now they can be sorted like the basic types:

std::sort(rain, rain + 240);
Comments