2017-07-19 69 views
1

在我的代碼有那些臺詞:在這種情況下,std :: map中的插入可能會失敗?

if(mymap.count(plan) == 0) { 
    std::vector<XYZ> v; 
    v.reserve(10); 
    mymap.emplace(plan, v); 
    std::cout << "Plan " << plan.normal << " @ " << plan.O << " added"; 
} 

//I inserted this code for debugging 
std::map<Plan, std::vector<XYZ>>::const_iterator it = mymap.find(plan); 
if(it == this->intersections.end()) 
    std::cout << "not found"; 

這怎麼可能,我可以在控制檯plan added和剛過not found讀?

我的地圖被宣佈爲:

std::map<Plan, std::vector<XYZ>, PlanComp> mymap; 

在某些時候,我thougt它來自於比較,但它尊重irreflexivity,反對稱,傳遞,等價的傳遞性(根據this blog這就足夠了):

struct PlanComp { 
    bool operator()(const Plan& l, const Plan& n) const { 
    return (l.O.x != n.O.x) || (l.O.y != n.O.y) || (l.O.z != n.O.z) 
      || (l.normal.x != n.normal.x) || (l.normal.y != n.normal.y) || (l.normal.z != n.normal.z); 
    } 
}; 

struct XYZ { 
    double x; 
    double y; 
    double z; 
}; 

struct Plan { 
    XYZ O; 
    XYZ plan; 
}; 
+1

比較器應該表現出「小於」語義 - 也就是嚴格的弱排序。你的似乎沒有這樣做。 –

+0

我不認爲你的「比較」尊重反對稱或傳遞性。 – LogicStuff

+0

這不足以定義訂單。 –

回答

2

你比較沒有定義strict weak ordering(嚴格地講,「小於」,它定義了你的元素的順序語義)。因此,您的代碼顯示未定義的行爲。

最簡單的解決辦法是使用辭書比較 - 比較x第一,那麼只有在平局的情況下比較y,等等。在C++ 11中更簡單;元組的operator <已經爲你做了這個(你可以使用std::tie來獲取元組)。示例請參閱Operator < and strict weak ordering的答案。

相關問題