Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting a vector of objects in C++

Tags:

c++

say I have a class "Information" and it stores the Name and Age of people in a vector.

so...

class Information {

private:
int age;
string name;

//etc, etc...
};

How would I sort the vector in either ascending/descending order with respect to age?

I believe you use something like this.

sort(listOfPeople.begin(), listOfPeople.end(), greater<Information>());

listOfPeople would be the vector.

Any help would be greatly appreciated.

like image 519
user432584920684 Avatar asked Aug 18 '11 04:08

user432584920684


1 Answers

If you want to sort them in non-descending order by age, one way to do it is to define a functor for comparison:

class CompareInformations {
    public:
    // after making CompareInformations a friend class to Information...
    operator(const Information& rhs, const Information& lhs) {
        return rhs.age < lhs.age;
    }
};

And then do your sort:

sort(listOfPeople.begin(), listOfPeople.end(), CompareInformations());

You could also overload operator< for your class, and do without the comparison object:

// inside your class
bool operator <(const Information& rhs) {
    return age < rhs.age;
}

Then sort it:

sort(listOfPeople.begin(), listOfPeople.end());

The above examples assume you want to sort in non-descending (almost ascending, but not quite) order. To do non-ascending order, just change all occurrences of < to >.

like image 71
Seth Carnegie Avatar answered Sep 25 '22 15:09

Seth Carnegie