2

我已经编写了如下代码。我收到分段错误错误。调试器显示错误来自“some_order”。我检查了一个特定示例的变量值。取 n = 26:然后, Var = {0,...,25} 这意味着传递给 'some_order' 的 u 和 v 必须在 (0-25) 范围内,但我得到其中一个的一些大值,例如 7785654或-1549259(类似的东西)。我不明白为什么。分段错误是不可避免的。

//TNT: template numeric toolkit
#include "tnt.h"  
//contains includes to all files in http://math.nist.gov/tnt/tnt_doxygen/files.html
//all other necessary stl and standard c++ libaray includes are there     

class global_data{
public:
  static TNT::Matrix<double>* Value_matrix;

};
TNT::Matrix<double>* global_data::Value_matrix = NULL;


bool some_order(const int& u ,const int& v) {
      return (*global_Data::Value_matrix)[v][u] == 0.0;
}

void some_function(int n){
    std::vector<int> Var(n);
    for(int i=0; i<n; i++){
        Var[i] = i;
    }
    std::sort(Var.begin(), Var.end(), some_order );
}

int main(){
    //assume we have n;       
    //nxn matrix, initialised with 0.0 
    global_data::Value_matrix = new TNT::Matrix<double>(n,n,0.0) ;
    //global_data::Value_matrix is then filled with values
    some_function(n); 
    delete[] global_data::Value_matrix
}
4

2 回答 2

5

std::sort假设比较函数建模严格弱排序

  • 不自反的:some_order(u, u)返回false
  • 反对称:some_order(u, v)暗示!some_order(v, u)(两者都可能是假的,在这种情况下uv是等价的)
  • 及物的:some_order(u, v) == truesome_order(v, w) == true暗示some_order(u, w) == true

这将取决于您的global_Data矩阵的内容是否some_order()可以与std::sort

- irreflexive: diagonal cannot have 0.0 on it
- anti-symmetric: if an entry has 0.0 then the transpose element has no 0.0
- transitive: if `global_Data[u, v]` and `global_Data[v, w]` have 0.0 then `global_Data[u, w]` also has that.

先验似乎是一个非常强的限制,您可能需要检查它。

于 2013-07-24T09:48:08.267 回答
5

这种类型的错误几乎总是由于排序函数不符合标准要求的严格弱排序的要求。你确定 1)some_order(a, b) && some_order(b, c)暗含some_order(a, c)2) some_order( a, b )暗含!some_order(b, a)吗?(在我看来,它看起来不像,但我真的不明白它在做什么。)

于 2013-07-24T09:46:40.317 回答