Sorting a vector of objects using two criteria

Let's say I have vector<People*> Population

with

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

      

and I would like to sort first name

and then city

, for example:

Anna, Alabama, 1284
Anna, New York, 8377
Daniel, Sydney, 8332
Peter, Alabama, 6392
Peter, Munich, 5590

      

I thought I would sort first name

, then sort city

internally name

, and then move on to the next name

.

Is there a better way?

+3


source to share


2 answers


You can pass a custom comparator 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;
});

      

+6


source


You can use comparison std::tuple

:

std::sort(Population.begin(), Population.end(),
    [](auto& p1, auto& p2) {
        return std::tie(p1->name, p1->city) < std::tie(p2->name, p2->city); 
    });

      



This way you can add more sorting fields very easily.

+2


source







All Articles