user2806423
user2806423

Reputation: 33

Sorting a list with objects by property

I'm completely stumped, looking around at examples hasn't helped me getting this sort function to work:

void sortRegistryByName(std::list<Transcript>& registry) {
   std::sort(registry.begin(), registry.end(), [](const Transcript &f, const Transcript &s) { return f.name < s.name; }); 
}

The code above should sort the list of Transcripts by their name property.

And the Transcript is as follows:

typedef struct Transcript_t {
    std::string name; // Name of the transcript
    std::string student_id;
    std::list<std::pair<std::string, size_t>> grades; // List of (course, grade) pairs
} Transcript;

When I try to compile this the sort function causes one huge wall of errors with something related to safe_iterators and operators.

Anyone see any really really silly mistake here? I'm blind to it.

Upvotes: 3

Views: 6657

Answers (1)

Paul Evans
Paul Evans

Reputation: 27577

You have to call std::list's sort function since it doesn't have random access iterators:

std::list<Transcript> registry;
registry.sort([](const Transcript &f, const Transcript &s) { return f.name < s.name; });

Upvotes: 7

Related Questions