0

I have structure:-

typedef struct {
int x;
int y;
}point;

i declared array :-

point A[100];

i took inputs for A from user. so how can we sort the array A on the basis of x element. I know how to do it by writing a function. But how to do it by using sort() function defined in algorithm.h in C++

4 Answers4

1

You can pass a compare function to std::sort.

point A[100];

std::sort(A, A+100, 
          [](const point& f, const point& s) -> bool{
              return f.x < s.x;
          });
cdonat
  • 2,748
  • 16
  • 24
0

You can pass a comparator function as the third argument of sort.

Include algorithm of course.

#include<algorithm>

Define the comparator function. It should compare two points and return true if the first one should be before the second one (if first one is smaller than the second one) in the sorted array. The sort function in <algorithm> will use this comparator function to compare your items and put them in the right order. You can learn more about sorting algorithms here. If you need more advanced materials you can lookup "Introduction to Algorithms".

bool compare(const point& p1, const point& p2) {
    return p1.x < p2.x;
}

Use sort and pass your array and the function like this:

int main () {
    point A[100];
    std::sort(A, A+100, compare);
    return 0;
}
Aᴍɪʀ
  • 7,623
  • 3
  • 38
  • 52
  • thanks Amir it worked,but as i am new to c++ can you explain how compare function is working . and why you are not passing any argument to compare .As it's function prototype declaration contains 2 arguments p1 and p2. – Gaurav Anand Jan 15 '16 at 06:23
  • @GauravAnand You're welcome. I updated the answer with a little more info. `sort` just need a function that could use it to compare two of your data-type. It will use this function as many times as possible with different items in your array to put them in the right order. – Aᴍɪʀ Jan 15 '16 at 06:27
0

Write comparator:

inline bool ComparePoints(const point & first, const point & second) {
    return first.x < second.x;
}

After that you can call std::sort():

std::sort(A, A + 100, ComparePoints);
SashaMN
  • 708
  • 5
  • 16
0

Using lambdas:

std::sort(std::begin(A),std::end(A),[](point const& l,point const& r){return l.x<r.x;});
Humam Helfawi
  • 19,566
  • 15
  • 85
  • 160