Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort a vector of objects by an object's attribute [duplicate]

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?

like image 248
dotty Avatar asked Mar 14 '12 17:03

dotty


People also ask

How do you sort a vector of an object?

You can sort a vector of custom objects using the C++ STL function std::sort. The sort function has an overloaded form that takes as arguments first, last, comparator. The first and last are iterators to first and last elements of the container.

How do you sort a vector without sorting?

The vector can use the array notation to access the elements. If you don't want to use the default std::sort , or std::sort with custom comparator, you can use qsort or write your own.

What is the sort function in C++?

The std::sort() Function in C++ The std::sort() function in C++ is a built-in function that is used to sort any form of data structure in a particular order. It is defined in the algorithm header file.


1 Answers

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;
}
like image 169
mfontanini Avatar answered Sep 27 '22 17:09

mfontanini