2012-05-10 47 views
0

我试图使用点矢量填充点图。我正在尝试做一个棋盘游戏,棋盘上的每个位置都有一个点(x,y)和法律移动向量(点对象)。将填充矢量填充到地图中

我似乎无法将地图KEY作为点。

struct Point 
{ 
    Point() {} 
    Point(int ix, int iy) :x(ix), y(iy) {} 

    int x; 
    int y; 
}; 


Point p_source (2,2); 
Point p_next1 (1,2); 
Point p_next2 (1,3); 
Point p_next3 (1,4); 

map <Point, vector<Point> > m_point; 

dict[p_source].push_back(p_next1); 
dict[p_source].push_back(p_next2); 
dict[p_source].push_back(p_next3); 

这是错误的,我得到

In member function 'bool std::less<_Tp>::operator()(const _Tp&, const _Tp&) const [with _Tp = Point]':|

instantiated from '_Tp& std::map<_Key, _Tp, _Compare, _Alloc>::operator[](const _Key&) [with _Key = Point, _Tp = std::vector, std::allocator >, std::allocator, std::allocator > > >, _Compare = std::less, _Alloc = std::allocator, std::allocator >, std::allocator, |

instantiated from here|

c:\program files (no match for 'operator<' in '__x < __y'| ||=== Build finished: 1 errors, 0 warnings ===|

回答

8

你的错误是完全无关std::vector<>std::map<>要求其键后,与operator<相媲美,或者你提供的一个自定义的比较器。最简单的办法是后Point的定义中加入如下:

bool operator <(Point const& lhs, Point const& rhs) 
{ 
    return lhs.y < rhs.y || lhs.y == rhs.y && lhs.x < rhs.x; 
} 
15

检查我最喜爱的网上参考it reads

template< 
    class Key, 
    class T, 
    class Compare = std::less<Key>, 
    class Allocator = std::allocator<std::pair<const Key, T> > 
> class map; 

Map is an associative container that contains a sorted list of unique key-value pairs. That list is sorted using the comparison function Compare applied to the keys. Search, removal, and insertion operations have logarithmic complexity. Maps are usually implemented as red-black trees.

既然你不提供一个明确的Compare它使用排序默认std::less<Key> 。好像我们是在正确的轨道上,因为错误是在类:

In member function 'bool std::less<_Tp>::operator()(const _Tp&, const _Tp&) const [with _Tp = Point]':|

让我们check that

template< class T > 
struct less; 

Function object for performing comparisons. Uses operator< on type T .

这符合什么样的错误信息告诉我们:

no match for 'operator<' in '__x < __y'

嗯,但没有operator<类型Point ...

+2

给答案是:好。解释错误:无价。 – chris