Gaurav Anand
Gaurav Anand

Reputation: 11

Sort structure array on basis of an element in c++ by sort() function defined in algorithm header file

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++

Upvotes: 0

Views: 934

Answers (4)

Humam Helfawi
Humam Helfawi

Reputation: 20324

Using lambdas:

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

Upvotes: 0

Aᴍɪʀ
Aᴍɪʀ

Reputation: 7803

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

Upvotes: 0

cdonat
cdonat

Reputation: 2822

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

Upvotes: 1

SashaMN
SashaMN

Reputation: 708

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

Upvotes: 0

Related Questions