2016-04-05 40 views
-1

我正在使用multiset來存儲訂購對象的集合,我使用運算符<來建立順序標準,但我做錯了什麼,因爲當我通過multiset遍歷打印跟蹤時,我可以看到他們是不是在所有訂購....我真的阻止這個問題...STL multiset設置插入順序C++

我儘量簡化這裏我的代碼:

class CellSearch 
{ 
    public: 
     bool operator<(const CellSearch & C) const; 
     int getF() const  { return _G + _H; } 
    private: 
     int _G; 
     int _H; 
} 
... 
bool CellSearch::operator< (const CellSearch& C) const 
{ 
    return (this->getF() < C.getF()); 
} 

我宣佈多重集的方式是:

std::multiset<CellSearch*> myOpenList; 

我插入一個新元素是這樣的:

.... 
CellSearch *actualSearch = new CellSearch(start); 
addOpenList(actualSearch, myOpenList); 

這裏是功能:

void Grid::addOpenList(CellSearch* actual, std::multiset<CellSearch*>& openList) 
{ 
    openList.insert(actual); 
} 

是我第一次使用多集...其實我不是一個向量第一容器:)你可以在這裏看到錯誤嗎?

我試圖總結代碼,希望不要太多......

回答

4

你多集的存儲指針對象。因此,作爲比較,它比較指針,而不是對象本身。

要使其以當前形式工作,您需要將對象自己放入多重集。另一個選擇是提供一個自定義的比較器來設置,這將知道取消引用一個指針並比較實際的對象 - 但在這種情況下,這比較低劣,因爲我沒有看到任何存儲指針的理由。

operator <作爲自由函數而不是類成員來實現也更好。

如果你在你的容器,其具有指針設置,這是你應該怎麼做:

template<class KEY> 
struct pointer_compare { 
    bool operator()(const KEY* lhs, const KEY* rhs) const { 
     return *lhs < *rhs; 
    } 
} 

std::multiset<Search*, pointer_compare<Search>> myOpenList 
+0

謝謝你的建議! :)無論如何,請你舉一個例子來說明怎樣才能比較取消引用指針來比較對象? – Breikdans

+0

@Breikdans - 完成了,但我真的反對它。 – SergeyA

+0

非常感謝!我會考慮不要存儲指針的選項,但是mw學習如何比較指向指針的方法非常有趣:) – Breikdans

1

的問題是,你不設定CellSearch對象的工作,而是指向他們,這使得比較器可以使用指針。

這裏是通用的解決方案,你可以重用爲其他指針比較:

template<class T> 
struct PointerComparator { 
    bool operator()(const T *a, const T *b) const { 
     return *a < *b; 
    } 
}; 

std::multiset<CellSearch*, PointerComparator<CellSearch> > myOpenList; 

這樣,你仍然有你的operator <CellSearch定義。

+0

非常感謝您的幫助! – Breikdans

0

可以定義一個小區的較少仿函數是這樣的:

class cmpCell 
{ 
    bool operator()(CellSearch* a, CellSearch* b) 
    { 
     return *a < *b; 
    } 
}; 

,然後用它當聲明多重集:

std::multiset<CellSearch*, cmpCell> myOpenList;