c++ sort vector of objects by property
To sort a vector of objects by a specific property in C++, you can follow these steps:
- Overload the less than (<) operator in the class of the objects you want to sort.
- Use the std::sort algorithm from the
header, providing the begin and end iterators of the vector, and a lambda function that compares the desired property of the objects.
Here's an example:
#include <iostream>
#include <vector>
#include <algorithm>
class Person {
public:
std::string name;
int age;
bool operator<(const Person& other) const {
return age < other.age; // Sort by age
}
};
int main() {
std::vector<Person> people = {{"Alice", 25}, {"Bob", 20}, {"Charlie", 30}};
std::sort(people.begin(), people.end(), [](const Person& a, const Person& b) {
return a.age < b.age; // Sort by age
});
for (const auto& person : people) {
std::cout << person.name << " - " << person.age << std::endl;
}
return 0;
}
This code will sort the vector of Person objects by the "age" property in ascending order.