compare function of sort in c++ for index sort

╄→гoц情女王★ 提交于 2020-01-16 23:10:18

问题


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


回答1:


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.




回答2:


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



来源:https://stackoverflow.com/questions/15283897/compare-function-of-sort-in-c-for-index-sort

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!