2014-02-28 24 views
0

map::find利用map::key_comp來搜索關鍵字。默認map::key_comp適用於我猜測的數據類型。 我有一個對象指針std::map<A*, B*)的地圖,並希望找到一個對象指針A。 是否可以重載map :: key以便我可以使用乾淨的map::find語義?如果是這樣,怎麼樣? 據我所知,std::find_if可能是一個使用,但我只是想知道,如果這個選項是可能的。重載map :: key_comp,以便我可以在對象指針的地圖上使用map :: find

我想重載map::key_comp的另一個原因是,對於用戶創建的類,默認比較沒有任何意義。所以std::map不能按照我希望的方式按鍵排序(使用我的對象比較邏輯)。

回答

0

您可以用自定義比較,在這裏你可以添加你比較邏輯聲明地圖

struct structMyObjectAComparer 
    { 
     bool operator()(const A* pLeft, const A* pRight) 
     { 

     } 
    }; 

std::map<A*, B*, structMyObjectAComparer> myMap 
1

看看指定一個比較模板參數時,您可以在定義地圖:

class CompareIntPtr 
{ 
public: 
    bool operator()(int* p1, int* p2) 
    { 
     return *p1 < *p2; 
    } 
}; 

int main() { 

    typedef std::map< int*, int, CompareIntPtr > TestMapType; 
    TestMapType m; 

    int *i1 = new int(1); 
    int *i2 = new int(2); 

    m.insert(std::make_pair(i1, 1)); 
    m.insert(std::make_pair(i2, 2)); 

    TestMapType::const_iterator found = m.find(i1); 
    if(found != m.end()) 
     std::cout << "Found i1"; 

    return 0; 
} 
相關問題