8

Possible Duplicate:
How to use std::sort with a vector of structures and compare function?

I have a cat object (what?) and a catSort object which obviously sorts the cat objects. Below is the classes

class cat {
public:
    int age;
};

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

void catSorter::AddCat(cat new_cat){
    this->cats.push_back(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;
sorter->AddCat(tim);
sorter->AddCat(mark);
sorter->AddCat(phil);

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

I'm having difficulties sorting a vector, how would I go about doing this? Should I just loop through the cats attribute and store them inside a temporary vector then return that? Is there an easier way to do this?

Community
  • 1
  • 1
dotty
  • 40,405
  • 66
  • 150
  • 195
  • [lookup the std::sort](http://msdn.microsoft.com/en-us/library/ecdecxh1(v=vs.80).aspx) You'll want to use a predicate to tell it how to sort `cat` objects. – Mooing Duck Mar 14 '12 at 17:03

1 Answers1

25

You should implement an operator< on cat so that cats can be sorted:

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

You can then include the "algorithm" header and use std::sort on your array:

vector< cat > catSorter::SortCatsByAge(){
   vector< cat > cats_copy = cats;
   std::sort(cats_copy.begin(), cats_copy.end());
   return cats_copy;
}
mfontanini
  • 21,410
  • 4
  • 65
  • 73
  • 2
    What if you don't have access to the `cat` class, or you want to sort by different properties for different purposes? – Drew Noakes Nov 03 '13 at 22:31
  • 2
    @DrewNoakes you can define `operator<` as a free function or provide a custom compare function as the third argument to `std::sort`. – mfontanini Nov 03 '13 at 22:51
  • Why should `std::sort(cats_copy.begin(), cats_copy.end());` sort by age? How about fur length or cat's name alphabetically? – Jonny Apr 04 '16 at 06:14