xnl96
xnl96

Reputation: 189

How can I sort a list of struct pointers according to one of the struct's fields?

I have this code:

struct nod
{
    nod *vCap;
    int vCost;
    char vInfo;
}; 

list<nod*> vList;

for (int i = 9; i >= 0; i--) 
{
    nod *vTmp;
    vTmp->vCost=i;
    vTmp->vInfo='a';
    vList.push_back(vTmp);
}

How can I sort the list by the vCost value?

Upvotes: 1

Views: 3881

Answers (3)

Jerry Coffin
Jerry Coffin

Reputation: 490148

If the normal or natural ordering for a nod is by cost, then you might want to define its operator< to do that:

struct nod{
    nod*vCap; 
    int vCost;
    char vInfo;

    bool operator<(nod const &other)  { return vCost < other.vCost; }
};

Then, of course, you almost certainly want to create a list<nod> instead of a list<nod*>. Having done that, sorting items in a list will just be vList.sort();.

Just FWIW, you also need to fix a typo in your definition of nod (you have a comma instead of a semicolon between the definitions of vCost and vInfo.

Upvotes: 2

Mike Seymour
Mike Seymour

Reputation: 254471

You'll need a custom comparator to compare the field you're interested in:

struct compare_nod_by_cost {
    bool operator()(nod const * a, nod const * b) {
        return a->vCost < b->vCost;
    }
};

Then you can provide it as the comparator for list::sort:

vList.sort(compare_nod_by_cost());

In C++11, you can compress this into a lambda:

vList.sort([](nod const * a, nod const * b) {return a->vCost < b->vCost;});

(Note that you almost certainly want to store objects, rather than pointers, in your list; in that case, change the comparator's pointer arguments to references).

Upvotes: 5

Kerrek SB
Kerrek SB

Reputation: 477070

Use a lambda:

vList.sort([](const nod * a, const nod * b ) { return a->vCost < b->vCost; });

Upvotes: 2

Related Questions