比较字符串时出现分段错误

时间:2014-07-25 08:45:05

标签: c++ segmentation-fault

在我的程序中,有一部分需要对struct数组进行排序。 一切都很顺利,直到最后我想。 对于某些条目,一切都很好,直到数组末尾的一些条目。 在那里它引发了分段错误,我不知道为什么。

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之间,以及我在数组末尾的思考方式。但我不知道为什么

3 个答案:

答案 0 :(得分:1)

如果我没错,要对2个结构进行排序,你必须比较整个结构,而不仅仅是一个字段。而且您只是比较 n_timestamp 字段。其次,你不要把&lt; =放在比较中,而只是&lt;或&gt;。

这是运算符重载的示例:

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);
}
希望这会有所帮助。请问我是否不清楚!

答案 1 :(得分:0)

多一点来源会很好......

但首先:在相等的情况下,compare应该返回0,所以你的

if ( a_timestamp.n_timestamp.compare(b_timestamp.n_timestamp) <= 0)

没有任何意义......否则(如果它的意图)你的功能名称会产生误导。

要弄清楚,你的分段错误来自哪里,我们需要看到更多的源代码,但是分段错误表明你试图从空指针访问nestet值,所以在你的情况下似乎是你的一个比较结构从未创建过...... 哪个可以并且应该由if (null == x)返回false检查;或类似的东西

答案 2 :(得分:0)

比较函数应满足弱排序原则。

按以下方式更改功能

static bool compareStrings( const overview_table &a_timestamp, 
                            const overview_table &b_timestamp )
{
   return a_timestamp.n_timestamp < b_timestamp.n_timestamp;
}
相关问题