Sorting a vector of features by feature attribute

Possible duplicate:
How to use std :: sort with a vector of structs and a comparison function?

I have a cat object (what?) And a catSort object that obviously sorts cat objects. Following are the classes

class cat {
    int age;

class catSorter {
    vector< cat > cats;
    vector< cat > SortCatsByAge();
    void AddCat( cat new_cat );

void catSorter::AddCat(cat new_cat){

vector< cat > catSorter::SortCatsByAge(){
    // Sort cats here by age!

cat tim;
tim.age = 10;

cat mark;
mark.age = 20

cat phil;
phil.age = 3;

catSorter sorter;

std::<vector> sortedcats = sorter->SortCatsByAge();


I am having difficulty sorting a vector, how would I go about it? Should I just loop through the attribute cats

and store them in a temp vector and then return that? Is there an easier way to do this?


source to share

1 answer

You must use operator<

for a cat so that cats can be sorted:

class cat {
    int age;
    bool operator< (const cat &other) const {
        return age < other.age;


Then you can include the "algorithm" header and use std::sort

in your array:

vector< cat > catSorter::SortCatsByAge(){
   vector< cat > cats_copy = cats;
   std::sort(cats_copy.begin(), cats_copy.end());
   return cats_copy;




All Articles