Question

I have a vector below vector<int> jobs;

Within it I have a bunch of numbers lets say [4,6,2,7,262,15,623,9]

How can i sort this vector from numbers highest to lowest? So that the highest numbers are in the front?

I tried using this but it didnt work. Program crashes.

struct myclass {
  bool operator() (int i,int j) { return (i<j);}
} myobject;

std::sort (JobPool.end(), JobPool.begin(), myobject);

Was it helpful?

Solution

You have the begin and end iterators in the wrong order. You should call std::sort as:

std::sort(JobPool.begin(), JobPool.end(), myobject);

Then you should make the comparator actually be one that works in reverse order:

struct myclass {
    bool operator()(int i, int j) const { return j<i; }
} myobject;

Then you should notice that the standard library already supplies std::greater:

std::sort(JobPool.begin(), JobPool.end(), std::greater<int>());
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top