I'm trying to order elements of array1 based on the sorted order of array2. In my case, both array1 and array2 are members of the same class and they are public. I'm trying to use a nested class within my class to write the compare() function of std::sort as a functor, so that the nested class can access array2. Here is the code:
#include <iostream>
#include <algorithm>
using namespace std;
class sort_test {
public:
sort_test() { //some initialization
}
int array1[10];
int array2[10];
int index[10];
void sorting() {
sort (index, index+5, sort_test::Compare());
}
class Compare {
public:
sort_test *s;
bool operator() (const int i, const int j) {
return (s->array2[i] < s->array2[j]);
}
};
};
int main(void) {
int res[5];
sort_test st;
st.array2[0] = 2;
st.array2[1] = 1;
st.array2[2] = 7;
st.array2[3] = 5;
st.array2[4] = 4;
st.array1[0] = 8;
st.array1[1] = 2;
st.array1[2] = 3;
st.array1[3] = 2;
st.array1[4] = 5;
for (int i=0 ; i<5 ; ++i) {
st.index[i] = i;
}
st.sorting();
for (int i=0 ; i<5; ++i) {
res[i] = st.array1[st.index[i]];
}
for (int i=0; i<5; ++i) {
cout << res[i] << endl;
}
return 0;
}
The code compiles fine but gets a segmentation fault. The expected output of the code is 2 8 5 2 3