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:


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).

Edited by it@61@sec: language correction

2 Years
Discussion Span
Last Post by it@61@sec

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... :-)

Edited by it@61@sec: comment

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.