使用两个标准对对象进行排序

Hic*_*man 3 c++ sorting vector

比方说,我有vector<People*> Population带

class People {
    string name;
    string city;
    int id;
};
Run Code Online (Sandbox Code Playgroud)

我想先排序name,然后排序city,例如:

Anna, Alabama, 1284
Anna, New York, 8377
Daniel, Sydney, 8332
Peter, Alabama, 6392
Peter, Munich, 5590
Run Code Online (Sandbox Code Playgroud)

我以为我会先排序name,然后city在a中排序name,然后转到下一个name.

有更好的方法吗?

eml*_*lai 6

您可以将自定义比较器传递给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;
});
Run Code Online (Sandbox Code Playgroud)