2011-06-06 39 views
0

我想那種std::vector使用algorithm::sort,但我得到的運行時錯誤 Invalid operator <的std ::向量和算法::排序,有什麼不對下面的代碼

以下是我的代碼。

struct Point { 
    double x_cord; 
    double y_cord; 
    int id; 
    Point(int d, double x, double y) { 
     x_cord = x; 
     y_cord = y; 
     id = d; 
    } 
}; 

struct compareX { 
    bool operator()(Point * left, Point* right) const { 
     if (left->x_cord < right->x_cord) 
      return true; 
     return true; 
    } 
}; 
struct compareY { 
    bool operator()(Point * left, Point* right) const { 
     if (left->y_cord <= right->y_cord) return true; 
     return true; 
    } 
}; 

現在,我在填充值後調用它。

std::sort(posVector.begin(), posVector.end(), compareX()); 
+0

運行時錯誤...?你有沒有注意到你的比較函數總是返回true? – 2011-06-06 19:49:03

回答

4

您的比較函數總是返回true!

2

您的比較函數似乎總是返回true。偶爾返回假可能是一個好主意。 (比較嚴肅)比較(x.y)的座標並不像看起來那麼微不足道 - 在實現它之前你可能要考慮一下。

0

Point類過載「<」運算符。

+0

你也可以這樣做:http://www.cplusplus.com/reference/std/utility/rel_ops/ – yasouser 2011-06-06 19:50:34

1

如果您正在使用std::vector<Point>則必須

struct compareX { 
    bool operator()(const Point& left, const Point& right) const { 
     return left.x_cord < right.x_cord; 
    } 
}; 
struct compareY { 
    bool operator()(const Point& left, const Point& right) const { 
     return left->y_cord < right->y_cord; 
    } 
}; 

你的代碼的問題是

  • 比較班接受指針而不是進行排序的對象(如果std::vector<Point>進行排序,即不std::vector<Point*> )。如果你正在排列指針的向量,那麼它很好。

  • 比較類包含錯誤輸入 - 總是返回true(前面已經提到)

  • compareY使用<=代替<。這是個壞主意,因爲標準算法(包括排序)期望的語義較少(而不是較低或較低的等價語義)。