How to sort a vector of structures in C++

1 Answer

0 votes
#include <algorithm>   // for std::sort
#include <iostream>
#include <vector>
#include <string>

// A simple structure representing a person
struct Person {
    std::string name;
    int age;
};

// Comparator function: sort by age (ascending)
bool compareByAge(const Person& a, const Person& b) {
    return a.age < b.age;
}

// Comparator function: sort by name (lexicographically)
bool compareByName(const Person& a, const Person& b) {
    return a.name < b.name;
}

int main() {
    std::vector<Person> people = {
        {"Emma", 32},
        {"Sophia", 25},
        {"Ellison", 29},
        {"Lyra", 23}
    };

    // Sort by age
    std::sort(people.begin(), people.end(), compareByAge);

    std::cout << "Sorted by age:\n";
    for (const auto& p : people) {
        std::cout << p.name << " (" << p.age << ")\n";
    }

    // Sort by name
    std::sort(people.begin(), people.end(), compareByName);

    std::cout << "\nSorted by name:\n";
    for (const auto& p : people) {
        std::cout << p.name << " (" << p.age << ")\n";
    }
}



/*
run:

Sorted by age:
Lyra (23)
Sophia (25)
Ellison (29)
Emma (32)

Sorted by name:
Ellison (29)
Emma (32)
Lyra (23)
Sophia (25)

*/

 



answered May 8 by avibootz
...