【问题标题】:Segmentation Fault while comparing strings比较字符串时出现分段错误
【发布时间】:2014-07-25 08:45:04
【问题描述】:

在我的程序中,有一部分我需要对结构数组进行排序。 一切都很顺利,直到我认为结束。 对于某些条目,一切都很好并且可以工作,直到数组末尾的某些条目。 它会引发分段错误,我不知道为什么。

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

【问题讨论】:

  • 我们缺少一半的代码来帮助您。
  • 是时候启动调试器了。
  • 试试a_timestamp.n_timestamp.compare(b_timestamp.n_timestamp) &lt; 0(或a_timestamp.n_timestamp &lt; b_timestamp.n_timestamp)。 std::sort 需要严格的弱顺序。 &lt;= 不是自反的,因此也不是严格的弱排序。

标签: c++ segmentation-fault


【解决方案1】:

如果我没记错的话,要对 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);
}

希望这会有所帮助。请问我是否不清楚!

【讨论】:

  • 当然你可以在返回括号内写你需要的任何东西,并根据你的需要调整比较的顺序。
【解决方案2】:

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

按如下方式更改函数

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

【讨论】:

    【解决方案3】:

    多一点源就好了...

    但首先:如果相等,比较应该返回 0,所以你的

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

    没有任何意义...否则(如果有意的话)您的函数名称具有误导性。

    要弄清楚您的分段错误来自何处,我们需要查看更多源代码,但分段错误表明您正在尝试从空指针访问嵌套值,因此在您的情况下,您的一个从未创建过比较结构... if (null == x) 可以并且应该检查哪个返回 false;或者类似的东西

    【讨论】:

      猜你喜欢
      • 2022-11-18
      • 1970-01-01
      • 1970-01-01
      • 2014-10-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多