C++ 比较字符串时出现分段错误
在我的程序中,有一部分我需要对结构数组进行排序。 我想直到最后一切都很好。 对于某些条目,在数组末尾的某些条目之前,一切都很好。 它抛出了一个分割错误,我不知道为什么C++ 比较字符串时出现分段错误,c++,segmentation-fault,C++,Segmentation Fault,在我的程序中,有一部分我需要对结构数组进行排序。 我想直到最后一切都很好。 对于某些条目,在数组末尾的某些条目之前,一切都很好。 它抛出了一个分割错误,我不知道为什么 struct overview_table{ string o_timestamp; string n_timestamp; string dbID; }; sort(overview.begin(),overview.end(),compareStrings); static bool compar
struct overview_table{
string o_timestamp;
string n_timestamp;
string dbID;
};
sort(overview.begin(),overview.end(),compareStrings);
static bool compareStrings(const overview_table &a_timestamp, const overview_table &b_timestamp){
cout << "744" << endl;
if ( a_timestamp.n_timestamp.compare(b_timestamp.n_timestamp) <= 0){
cout << "746" << endl;
return true;
} else {
cout << "749" << endl;
return false;
}
}
仅供参考:输出仅用于检查分段错误抛出的位置。它在744和746之间,以及我在阵列末尾的想法。但我不知道为什么再多一点资源就好了 但首先:如果相等,则compare应返回0,因此
if ( a_timestamp.n_timestamp.compare(b_timestamp.n_timestamp) <= 0)
没有任何意义。。。否则,如果它是有意的,那么函数的名称是误导性的
为了找出分段错误的来源,我们需要查看更多源代码,但分段错误表明,您试图从空指针访问嵌套集值,因此在您的情况下,似乎从未创建过一个比较结构。。。
如果null==x返回false,则可以且应该由;或者类似的东西如果我没有错的话,要对2个结构进行排序,你必须比较整个结构,而不仅仅是一个字段。您只比较n_timestamp字段。第二,你不需要放 这是操作员过载的一个示例:
bool operator<(const overview_table &a, const overview_table &b)
{
if ( a.n_timestamp.compare(b.n_timestamp) < 0) {return true;}
if ( a.n_timestamp.compare(b.n_timestamp) > 0) {return false;}
if ( a.o_timestamp.compare(b.o_timestamp) < 0) {return true;}
if ( a.o_timestamp.compare(b.o_timestamp) > 0) {return false;}
return a.dbID.compare(b.dbID);
}
希望这有帮助。如果我不清楚,请问我 比较函数应满足弱排序原则 按以下方式更改函数
static bool compareStrings( const overview_table &a_timestamp,
const overview_table &b_timestamp )
{
return a_timestamp.n_timestamp < b_timestamp.n_timestamp;
}
我们缺少能够帮助您的一半代码。是时候启动调试器了。请尝试使用\u timestamp.n\u timestamp.compareb\u timestamp.n\u timestamp<0或\u timestamp.n\u timestamp