我编写了类似下面的代码。我得到分段错误错误。调试器显示错误来自'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
}
答案 0 :(得分:5)
这种类型的错误几乎总是由于订购功能
不符合严格弱序的要求,如
标准要求。你确定1)some_order(a,
b) && some_order(b, c)
暗示some_order(a, c)
,那2)
some_order( a, b )
隐含!some_order(b, a)
? (手头,它
不看起来给我,但我真的不明白它是什么
正在做。)
答案 1 :(得分:5)
std::sort
假设比较函数模拟Strict Weak Ordering
some_order(u, u)
返回false
some_order(u, v)
隐含!some_order(v, u)
(两者都可能是假的,在这种情况下u
和v
是等效的)some_order(u, v) == true
和some_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.
先验似乎是一个非常强大的限制,你可能想检查一下。