【问题标题】:compare function of sort in c++ for index sort比较C++中排序的函数用于索引排序
【发布时间】:2013-03-07 23:27:10
【问题描述】:

我正在尝试根据 array2 的排序顺序对 array1 的元素进行排序。在我的例子中,array1 和 array2 都是同一个类的成员并且它们是公共的。我正在尝试在我的类中使用嵌套类将 std::sort 的 compare() 函数编写为仿函数,以便嵌套类可以访问 array2。代码如下:

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

代码编译良好,但出现分段错误。代码的预期输出是 2 8 5 2 3

【问题讨论】:

  • 那么到目前为止,您尝试了什么?你的调试器说问题是什么?
  • 问题可能在于//some initialization 是什么。它会初始化数组吗?
  • 段错误发生在哪一行?

标签: c++ sorting


【解决方案1】:
sort_test::Compare()

这会将Compare 对象中的指针初始化为null;所以当你尝试访问数组时,你会得到未定义的行为(实际上是分段错误,如果数组索引足够小)。

你想要

sort_test::Compare(this)

使用适当的构造函数初始化s:

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

在 C++11 中,您可以省略构造函数并使用 Compare{this} 对其进行初始化,但无论如何添加构造函数都是一个好主意,以使类不易出错。

【讨论】:

    【解决方案2】:

    比较运算符正在取消引用未初始化的指针s。这可能会导致异常。

    【讨论】:

      猜你喜欢
      • 2016-02-06
      • 2021-12-11
      • 2012-05-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多