#include <algorithm> // for std::sort
#include <iostream> // for std::cout
#include <string> // for std::string
#include <vector> // for std::vector
// ------------------------------------------------------------
// Example: Sorting a vector of structs that contain nested structs
// ------------------------------------------------------------
// A nested struct representing an address
struct Address {
std::string city;
int zip;
};
// A struct representing a person, containing a nested Address
struct Person {
std::string name;
int age;
Address address;
};
// ------------------------------------------------------------
// Comparison function:
// Sort by city name first, then by zip code, then by age.
// This demonstrates how to naturally access nested fields.
// ------------------------------------------------------------
bool comparePersons(const Person& a, const Person& b) {
// Compare by city
if (a.address.city != b.address.city)
return a.address.city < b.address.city;
// If cities are equal, compare by zip
if (a.address.zip != b.address.zip)
return a.address.zip < b.address.zip;
// If zip codes are equal, compare by age
return a.age < b.age;
}
// ------------------------------------------------------------
// Helper function to print the list
// ------------------------------------------------------------
void printPersons(const std::vector<Person>& people) {
for (const auto& p : people) {
std::cout << p.name
<< " | age: " << p.age
<< " | city: " << p.address.city
<< " | zip: " << p.address.zip
<< "\n";
}
}
// ------------------------------------------------------------
// Main program
// ------------------------------------------------------------
int main() {
// Create a sample list of people
std::vector<Person> people = {
{"Alice", 30, {"San Francisco", 42100}},
{"Bob", 40, {"Austin", 32000}},
{"Carol", 35, {"New York City", 42000}},
{"Dave", 25, {"Austin", 32000}},
{"Eve", 28, {"New York City",61000}}
};
// Sort using std::sort and our custom comparison function
std::sort(people.begin(), people.end(), comparePersons);
// Print the sorted result
printPersons(people);
}
/*
run:
Dave | age: 25 | city: Austin | zip: 32000
Bob | age: 40 | city: Austin | zip: 32000
Carol | age: 35 | city: New York City | zip: 42000
Eve | age: 28 | city: New York City | zip: 61000
Alice | age: 30 | city: San Francisco | zip: 42100
*/