2010-06-22 40 views
0

我有我使用作爲一個std關鍵::地圖的std ::地圖::找到()

struct PpointKey{ 
     unsigned int xp,yp; //pixel coordinates 

     unsigned int side; 

     PpointKey(unsigned xp,unsigned yp,unsigned side=5):xp(xp),yp(yp),side(side) 
     {} 


     bool operator==(const PpointKey& other) const{ 
       const unsigned int x = other.xp; 
       const unsigned int y = other.yp; 

       return ((x>=xp && x<=xp+side) && (y>=yp && y<=yp+side)); 
     } 

     bool operator<(const PpointKey& other) const{ 

       const unsigned int x = other.xp; 
       const unsigned int y = other.yp; 

       const unsigned other_distance_2 = x*x + y*y; 

       const unsigned this_distance_2 = this->xp*this->xp + this->yp * this->yp; 

       return this_distance_2 < other_distance_2; 
     } 
}; 

我想達成什麼是使用find一個簡單的結構( )使用xp,yp屬性距離在side以內的密鑰訪問地圖。換句話說,如果我有一個(X,Y)的元組,我想找到的地圖裏面是滿足運營商==功能

return ((x>=xp && x<=xp+side) && (y>=yp && y<=yp+side)); 

中的條件這可能使用找到的第一個PpointKey?我得到map.end(),所以我想檢查find()函數是否使用operator ==。也許搜索算法會更好?

在此先感謝。

+0

請記住,'std :: map'只使用'operator <'。如果兩個鍵都小於另一個,則認爲兩個鍵相等。 – 2010-06-22 07:09:10

回答

1

find功能map不使用operator==

但是,您可以使用std::find,傳入mapbegin()end()迭代器。它將一次只遍歷一個序列,併產生匹配的第一個對象(複雜性是線性的)。

您遇到的問題是由於您濫用了操作員超載。這裏的問題是,operator==常見的定義是:

T operator==(T lhs, T rhs) 
{ 
    return !(lhs < rhs) && !(rhs < lhs); 
} 

這是不是與你定義的情況下,你無法代替一個用於其他。

如果您使用傳統函數而不是運算符重載,而使用表達式名稱而不是運算符重載,那將是最好的選擇。請注意,mapstd::find允許您傳遞適當的謂詞對象,您不需要重載操作符以使用它們。

+0

但'std :: find()'會在'std :: pair ::'上運算符,而不是''Key'。所以'std :: find_if()'應該使用適當的謂詞,對吧? – sbi 2010-06-22 07:10:00