将矢量填充到地图中

byl*_*gja 0 c++ stl map

我试图用点矢量填充点地图.我试图制作棋盘游戏,棋盘上的每个位置都有一个点(x,y)和合法移动的矢量(Point对象).

我似乎无法将地图KEY作为Point.

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);
Run Code Online (Sandbox Code Playgroud)

这是我得到的错误

在成员函数'bool std :: less <_Tp> :: operator()(const _Tp&,const _Tp&)const [with _Tp = Point]':

实例化自'_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,|

从这里实例化

c:\ program files('__x <__y'中没有匹配'operator <'| ||| ===构建完成:1个错误,0个警告=== |

R. *_*des 15

检查我最喜爱的网上参考记载:

template<
    class Key,
    class T,
    class Compare = std::less<Key>,
    class Allocator = std::allocator<std::pair<const Key, T> >
> class map;
Run Code Online (Sandbox Code Playgroud)

Map是一个关联容器,包含唯一键值对的排序列表.该列表使用Compare应用于键的比较函数进行排序 .搜索,删除和插入操作具有对数复杂性.地图通常实现为红黑树.

由于您未提供显式,Compare因此使用默认值进行排序std::less<Key>.好像我们在正确的轨道上,因为错误在那个类中:

在成员函数'bool std :: less <_Tp> :: operator()(const _Tp&,const _Tp&)const [with _Tp = Point]':

我们来看看:

template< class T >
struct less;
Run Code Online (Sandbox Code Playgroud)

用于执行比较的函数对象.使用operator<类型T.

这与错误消息告诉我们的内容相符:

'__x <__y'中的'operator <'不匹配

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

  • 给出答案:好.解释错误:无价之宝. (2认同)

ild*_*arn 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;
}
Run Code Online (Sandbox Code Playgroud)