I have class and this class contains a number. And I have a vector contains object pointer of class. And I want to sort that objects according to their numbers. How can I do this?
Thanks for answers.
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
class Course
{
public:
Course (int code, string const& name) : name(n), code(c) {}
int getCourseCode() const { return code; }
string const& getName() const { return name; }
private:
string name;
int code;
};
int main()
{
vector<Course*> cor;
vector<Course*>::iterator itcor;
cor.push_back(new Course(3,"first"));
cor.push_back(new Course(2,"sekond"));
cor.push_back(new Course(4,"third"));
cor.push_back(new Course(1,"fourth"));
cor.push_back(new Course(5,"fifth"));
sort (cor.begin(), cor.end());
for (itcor=cor.begin(); itcor!=cor.end(); ++itcor) {
cout << *itcor << ' ';
}
}
For example when I want the sort the objects they are being sorted according to their adresses.
You can do this in three ways:
1) Overload the < operator, and call std::sort algorithm. The code will look like this:The first way is wrong, as you can’t overload the < operator in pointers.
2) Create a compare function, and then call the second version of
std::sort. The code looks like this:3) Create a compare class, which has it’s
()operator overloaded, and then call the third verion ofstd::sort. The code:Note: the sort function is found at the
algorithmheader file.