简体   繁体   English

如何根据结构的字段之一对结构指针列表进行排序?

[英]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? 如何按vCost值对列表进行排序?

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 : 然后,您可以将其作为list::sort的比较器:

vList.sort(compare_nod_by_cost());

In C++11, you can compress this into a lambda: 在C ++ 11中,您可以将其压缩为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). (请注意,您几乎肯定要在列表中存储对象,而不是指针;在这种情况下,请将比较器的指针参数更改为引用)。

使用lambda:

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

If the normal or natural ordering for a nod is by cost, then you might want to define its operator< to do that: 如果nod的正常或自然排序是按成本排序的,那么您可能需要定义其operator<来做到这一点:

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*> . 然后,当然,您几乎可以肯定要创建一个list<nod>而不是一个list<nod*> Having done that, sorting items in a list will just be vList.sort(); 完成之后,对列表中的项目进行排序将只是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 . 只是FWIW,您还需要修正nod的定义中的错字( vCostvInfo的定义之间用逗号代替分号)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM