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
  • 1
    Do you know how to write operator<? Commented Jan 15, 2016 at 6:10
  • 2
    Read more about std::sort and what it uses for comparison. Then learn about operator overloading. Commented Jan 15, 2016 at 6:11
  • No I don't know how to write operator< . Commented Jan 15, 2016 at 6:15
  • If you don't have a good beginners book yet, then you should find one. Then read the chapter on operator overloading. Commented Jan 15, 2016 at 6:17

4 Answers 4

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;
          });
Sign up to request clarification or add additional context in comments.

Comments

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

2 Comments

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

Comments

0

Using lambdas:

std::sort(std::begin(A),std::end(A),[](point const& l,point const& r){return l.x<r.x;});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.