comparator for sorting vector of struct in c++

Sure! Here is an example of a comparator for sorting a vector of structs in C++:

#include <iostream>
#include <vector>
#include <algorithm>

struct Person {
    std::string name;
    int age;
};

bool compareByAge(const Person& lhs, const Person& rhs) {
    return lhs.age < rhs.age;
}

int main() {
    std::vector<Person> people = {{"Alice", 25}, {"Bob", 30}, {"Charlie", 20}};

    std::sort(people.begin(), people.end(), compareByAge);

    for (const auto& person : people) {
        std::cout << person.name << " - " << person.age << std::endl;
    }

    return 0;
}

Explanation:

  1. We start by including the necessary header files: <iostream> for input/output, <vector> for using vectors, and <algorithm> for using the std::sort function.

  2. We define a struct called Person which has two members: name of type std::string and age of type int. This struct represents the data we want to sort.

  3. We define a function called compareByAge that takes two const references to Person objects and returns a bool value. This function is the comparator that will be used by std::sort to determine the order of the elements in the vector.

  4. Inside the compareByAge function, we compare the age member of the two Person objects using the < operator. This comparison determines the sorting order - if the age of the first person is less than the age of the second person, the function returns true, indicating that the first person should come before the second person in the sorted order.

  5. In the main function, we create a vector called people and initialize it with three Person objects, each with a name and age.

  6. We call std::sort and pass in the people vector as well as the compareByAge function as arguments. This sorts the vector in ascending order based on the age member of the Person objects.

  7. Finally, we iterate over the sorted people vector using a range-based for loop and print out the name and age of each person.

This example demonstrates how to define a comparator function and use it with the std::sort function to sort a vector of structs based on a specific member variable.