2012-05-10 48 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