-4
#include<bits/stdc++.h>

using namespace std;
struct node{
    long long int d;
    long long int e;
};

int main() {
    long long int n,q,i,f;
    scanf("%lld%lld",&n,&q);
    struct node *a=(struct node *)malloc(n*sizeof(struct node));
    struct node *c=(struct node *)malloc(sizeof(struct node));
    for(i=0;i<n;i++){
        scanf("%lld",&f);
        a[i].d=f;
        a[i].e=i;
    }
}

If I want to sort this array only by the 'd' parameter, then how would I do so using the sort function prescribed in stl? I want to sort this array while preserving the index. If the array followed by the index on the next line is:

4 2 1 3

0 1 2 3

Then I want my output to be:

1 2 3 4

2 1 3 0
sg7
  • 6,108
  • 2
  • 32
  • 40
Adit Jain
  • 17
  • 3

2 Answers2

0

Try this:

// ...
bool my_compare(const node &i, const node &j)
{
    return i.d < j.d;
}

// ...

std::sort(a, a+n, my_compare);

or use std::stable_sort if you want a stable sort. Although not needed in this case, as commented below, a lambda compare function with no capture could also be used:

std::sort(a, a+n, [](const node &i, const node &j){return i.d < j.d});
rcgldr
  • 27,407
  • 3
  • 36
  • 61
  • 3
    Or with a lambda: `std::sort(a, a+n, [](const node &a, const node &b){return a.d < b.d;});` – HolyBlackCat Mar 09 '18 at 19:18
  • @JesperJuhl - I updated my answer to include this option, but since there's no capture in this case a lambda function is not needed. – rcgldr Mar 09 '18 at 22:22
0

simply overload the operator inside struct then sort the array.

struct node{
    long long int d;
    long long int e;
    bool operator<(const node & other) const {
        return d<other.d;
    }
};

sort(a,a+n);