I have the following struct definition:

struct finfo {
 string filename;
 long fsize;

 bool operator() (finfo i, finfo j){return (i.fsize > j.fsize);}

} fstruct;

And the following vector definition:

vector<finfo> fdata;

In the code I use the following statement to sort the vector elements by fsize:

sort(fdata.begin(),fdata.end(),fstruct);

This works perfectly well, but how can I sort by the field "filename" when i.fsize = j.fsize ?
(The vector is filled by reading directory information, and putting the filenames and filesizes in the appropriate fields in the struct. If the filesize is equal I want to sort the files alphabetically by file name (the field filename).

Something like this:

if(i.fsize != j.fsize) return i.fsize < j.fsize;
else return /* compare filenames here */

There are other ways to organize the if-chain; this one makes the most sense to me because the higher-precedence comparison appears first.

You can change your function to the following to take into account the filename.

bool operator() (finfo i, finfo j)
{
    if(i.fsize == j.fsize)
        return i.filename > j.file
    return (i.fsize > j.fsize)
}

Thanks to both gusano79 and NathanOliver!
To get it sorted in alphabetic order from A to Z I had to change the statement from "i.filename > j.filename" to "i.filename < j.filename", but that's just a minor detail... :-)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.