Sorting vector of objects by one of their attributes

I have a vector of Car* objects - vector<Car*> cars

Each object in the vector has an integer attribute called passengers, which can be returned using the function getPassengers().

How do I sort the vector by the objects' passenger int? I know I need to use sort() and presumably a comparison function but I'm not quite sure how.

Thanks for your help.
Assuming you can guarantee that the pointers are valid and non-null,

1
2
3
    sort(v.begin(), v.end(), [](const Car* lhs, const Car* rhs) {
             return lhs->getPassengers() < rhs->getPassengers();
         });


or, for C++98,

1
2
3
4
5
6
7
8
9
struct CompareCars {
    bool operator()(const Car* lhs, const Car* rhs) const {
         return lhs->getPassengers() < rhs->getPassengers();
    }
};
// ...
int main() {
// ...
    sort(v.begin(), v.end(), CompareCars());

Last edited on
or without functors
1
2
3
4
5
6
7
8
compareCars(const Car* lhs, const Car* rhs)
{
    return lhs->getPassengers() < rhs->getPassengers();
}

/*...*/

std::sort(cars.begin(), cars.end(), compareCars);
Last edited on
Topic archived. No new replies allowed.