将矢量填充到地图中

populating vector into map

本文关键字:地图 填充      更新时间:2023-10-16

我正在尝试用点向量填充点地图。我正在尝试制作一个棋盘游戏,其中棋盘上的每个位置都有一个点 (x,y( 和合法移动向量(点对象(。

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

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);

这是我得到的错误

在成员函数 'bool std::less<_Tp>::operator(((const _Tp&, const _Tp&( 常量 [_Tp = 点]':|

实例化自'_Tp& std::map<_Key, _Tp, _Compare, _Alloc>::operator[](const _Key&( [_Key = 点,_Tp = std::vector, std::分配器>, std::分配器, std::分配器>>>, _Compare = std::less, _Alloc = std::分配器, 标准::分配器>, 标准::分配器, |

从这里实例化|

C:\Program Files ( 与 '__x <__y' 中的 'operator<' 不匹配| ||=== 构建完成:1 个错误,0 个警告 ===|

查看我最喜欢的在线参考资料,上面写着:

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

Map 是一个关联容器,其中包含一个排序列表 键值对。该列表使用比较功能排序 Compare应用于按键。搜索、删除和插入操作 具有对数复杂性。地图通常实现为红黑 树。

由于您没有提供显式Compare因此它使用默认std::less<Key>进行排序。似乎我们走在正确的轨道上,因为错误在该类中:

在成员函数 'bool std::less<_Tp>::operator(((const _Tp&, const _Tp&( 常量 [_Tp = 点]':|

让我们检查一下:

template< class T >
struct less;

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

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

与"__x <__y"中的"运算符<"不匹配

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

您的错误与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;
}