假设我有vector<People*> Population

class People {
    string name;
    string city;
    int id;
};

我想先按name排序,然后再按city排序,例如:
Anna, Alabama, 1284
Anna, New York, 8377
Daniel, Sydney, 8332
Peter, Alabama, 6392
Peter, Munich, 5590

我当时想我先按name排序,然后按city中的name排序,然后移至下一个name

有更好的方法吗?

最佳答案

您可以将自定义比较器传递给 std::sort :

std::sort(Population.begin(), Population.end(), [](People* a, People* b) {
    if (a->name != b->name) return a->name < b->name;
    return a->city < b->city;
});

关于c++ - 使用两个条件对对象的 vector 进行排序,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/42940528/

10-08 22:25
查看更多