2012-06-05 81 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