簡體   English   中英

C ++中帶有自定義排序運算符的分段錯誤

[英]Segmentation fault with custom sort operator in C++

以下代碼從文件中讀取輸入。 文件中的每一行都由一對整數和一個雙精度組成。

讀取值后,將其存儲到名為PNodestruct

#include <iostream>
#include <fstream>

#include <algorithm>
#include <vector>

struct PNode {
    int xi; 
    int ri; 
    double H;

    bool operator<(const PNode& rhs) const {
        if (ri > rhs.ri) return true;
        if (H < rhs.H) return true;
        return false;
    }   
};  

int main(int argc, char* argv[]) {

    if (argc != 2) { 
        std::cout << "usage: " << argv[0] << " input" << std::endl;
        return -1;
    }

    std::vector<PNode> v;
    std::ifstream f(argv[1]);

    int xi = -1;
    int ri = -1;
    double H = -1;

    while(f >> xi >> ri >> H) v.push_back(PNode{xi, ri, H}); 

    for (auto& x : v) std::cout << x.xi << "\t" << x.ri << "\t" << x.H << std::endl;
    std::sort(v.begin(), v.end());
    for (auto& x : v) std::cout << x.xi << "\t" << x.ri << "\t" << x.H << std::endl;

    return 0;
}

數據結構PNode具有內部定義的operator< ,用於對PNode進行排序。

但是,在某些輸入上,代碼發出分段錯誤。

Failing input

0 2 12
1 3 210.618
2 4 57.8743
3 4 155.022
4 2 8
5 4 0
6 3 90.8939
7 4 2
8 5 96.3038
9 3 95.268
10 4 650.056
11 2 32.2647
12 3 30.7549
13 2 29.2451
14 4 0
15 2 0
16 5 191.284
17 4 234.158
18 2 115.349
19 4 348.659
20 3 0
21 2 283.372
22 4 8
23 4 328.962
24 2 46.2444
25 4 2
26 3 142.561

Working input

0 2 29.7149
1 2 441.595
2 2 25.2916
3 2 1149.05
4 2 364.557

使用以下標志編譯了代碼:

g++ -g3 -std=c++11 test.cpp 

執行:

valgrind --leak-check=full ./a.out IN

valgrind報告的前幾行錯誤:

Conditional jump or move depends on uninitialised value(s)
==26785==    at 0x4013BC: PNode::operator<(PNode const&) const (test.cpp:13)
==26785==    by 0x4027A0: bool __gnu_cxx::__ops::_Iter_less_iter::operator()<__gnu_cxx::__normal_iterator<PNode*, std::vector<PNode, std::allocator<PNode> > >, __gnu_cxx::__normal_iterator<PNode*, std::vector<PNode, std::allocator<PNode> > > >(__gnu_cxx::__normal_iterator<PNode*, std::vector<PNode, std::allocator<PNode> > >, __gnu_cxx::__normal_iterator<PNode*, std::vector<PNode, std::allocator<PNode> > >) const (predefined_ops.h:43)

我同意@Slava的評論。

我建議對該功能進行一些改進。

bool operator<(const PNode& rhs) const {
    if (ri != rhs.ri)
    {
       return (ri > rhs.ri);
    }
    return (H < rhs.H);
}   

您的PNode::operator<不滿足嚴格的弱排序要求。

可能的解決方法:

bool operator<(const PNode& rhs) const {
    if (ri > rhs.ri) return true;
    if (ri < rhs.ri) return false;

    return H < rhs.H;
}  

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM