Search code examples
c++containersstdlist

C++ Own comparison in std::list


I have some structure in my program and list of them. It's something like this:

struct person{
    string name;
    char relation;
    string child;
}
typedef std::list < person > listP;

listP MyList;

I want sort this list by person.name using std::list::sort() but I don't know how to deal with it. I tried to find how to use STL custom comparisons, but now it's little to strange for me, so please explain this humanly :P


Solution

  • list::sort requires a predicate function-object.

    You can try:

    std::list<person> people;
    
    // Add some people...
    
    people.sort([](const person &left, const person &right)
    {
        return left.name < right.name;
    });
    

    See also:

    Sorting a list of a custom type