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:
We start by including the necessary header files:
<iostream>
for input/output,<vector>
for using vectors, and<algorithm>
for using thestd::sort
function.We define a
struct
calledPerson
which has two members:name
of typestd::string
andage
of typeint
. This struct represents the data we want to sort.We define a function called
compareByAge
that takes twoconst
references toPerson
objects and returns abool
value. This function is the comparator that will be used bystd::sort
to determine the order of the elements in the vector.Inside the
compareByAge
function, we compare theage
member of the twoPerson
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 returnstrue
, indicating that the first person should come before the second person in the sorted order.In the
main
function, we create a vector calledpeople
and initialize it with threePerson
objects, each with a name and age.We call
std::sort
and pass in thepeople
vector as well as thecompareByAge
function as arguments. This sorts the vector in ascending order based on theage
member of thePerson
objects.Finally, we iterate over the sorted
people
vector using a range-basedfor
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.