简体   繁体   中英

compare function of sort in c++ for index sort

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

The compare operator is dereferencing an uninitialized pointer s . That would likely result in an exception.

sort_test::Compare()

This initialises the pointer in the Compare object to null; so you'll get undefined behaviour (a segmentation fault in practice, if the array indexes are small enough) when you try to access the arrays.

You want

sort_test::Compare(this)

with an appropriate constructor that initialises s :

explicit Compare(sort_test * s) : s(s) {}

In C++11, you could leave out the constructor and initialise it with Compare{this} but adding the constructor is a good idea anyway, to make the class less error-prone.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM