2012-06-05 35 views
1

我已經試過的指數來寫這個代碼:不能使用結構作爲地圖

#include <iostream> 
#include <map> 

using namespace std; 

typedef struct 
{ 
    int x; 
    int y; 
}position; 

int main(int argc, char** argv) 
{ 
    map<position, string> global_map; 
    position pos; 
    pos.x=5; 
    pos.y=10; 
    global_map[pos]="home"; 
    return 0; 
} 

事實上,這不是原來的代碼,但簡化了它的版本(我想使與OpenGL的俄羅斯方塊遊戲)。
無論如何,這個問題是一個語法錯誤,我說:「global_map [pos] =」home「;」。
我沒有得到錯誤的原因,我張貼在這裏,誰需要更多的細節:

invalid operands to binary expression (' position const' and 'position const') 
+2

你爲什麼在C++中使用'typedef'結構? –

回答

6

關聯容器,這std::map是一個要求是必須有用作鍵的元素之間的排序。默認情況下,這是std::less,它簡單地稱爲operator <。因此,您只需使用struct作爲std::map中的密鑰就可以實現operator <

struct position 
{ 
    int x; 
    int y; 
}; 

bool operator <(position const& left, position const& right) 
{ 
    return left.x < right.x || (left.x == right.x && left.y < right.y); 
} 
1

您需要重載'<'比較運算符,以便映射到(除其他外)插入新元素。

bool operator<(const position&, const position&);

2

假設你確實要在1維結構的positionstd::map(而不是在某種二維結構的),則可以像下面這樣做在C++ 11:

#include <iostream> 
#include <map> 

using namespace std; 

typedef struct 
{ 
    int x; 
    int y; 
}position; 

int main(int argc, char** argv) 
{ 
    auto cmp = [](const position& a, const position& b) -> bool { 
     if (a.x == b.x) 
      return a.y < b.y; 
     return a.x < b.x; 
    }; 

    map<position, string, decltype(cmp)> global_map(cmp); 
    position pos; 
    pos.x=5; 
    pos.y=10; 
    global_map[pos]="home"; 
    return 0; 
} 

請根據自己的喜好調整cmp