0

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);

soniccool
  • 5,790
  • 22
  • 60
  • 98
  • 1
    http://en.cppreference.com/w/cpp/algorithm/sort – chris May 13 '14 at 05:22
  • 2
    "Program crashes" is a terrible description. Post the whole code of a program that crashes, if you want to get useful answers, and describe what input you are giving to cause the crash. Try to trim out as much code as possible from your program. – M.M May 13 '14 at 05:22
  • Ah isee there is `std::reverse(myvector.begin(),myvector.end());` – soniccool May 13 '14 at 05:23
  • 1
    If you use `rbegin` and `rend` then it will do a reverse sort in one go. – M.M May 13 '14 at 05:25
  • @sonicboom, No need to add that on top. See my link. It has two examples where it sorts in descending order and other examples that can be adapted. – chris May 13 '14 at 05:25
  • Why do you think std::sort (JobPool.begin(), JobPool.end()) is from begin to end, while std::sort (JobPool.end(), JobPool.begin()) is from end to begin? – cbel May 13 '14 at 05:26

1 Answers1

3

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>());
Mankarse
  • 39,818
  • 11
  • 97
  • 141