c++处理结构的映射
c++ working with maps of structs
Point是以下形式的结构:
typedef struct Point {
int x;
int y;
bool operator<(const Point &other) const
{
return ((this->x < other.x) && (this->y < other.y));
};
bool operator!=(const Point &other) const
{
return ((this->x != other.x) || (this->y != other.y));
}
bool operator==(const Point &other) const
{
return ((this->x == other.x) && (this->y == other.y));
}
} Point;
我使用的是:
map<Point,int> points;
映射是用{{0,0},1}初始化的。该程序使用points.count(p)来检查点p是否是点图中的关键
出现问题,程序总是返回yes!即使是地图上没有的点。我的意思是,如果p不是积分的关键,我就得到了积分。count(p)==1(而不是0)
此外,当使用points.find(p)让迭代器检查接收到的点是否真的==0(事实并非如此)时,我得到了一个完全不同的点的引用
知道怎么解决这个问题吗?
您的operator<()
定义不正确。假设我有a=Point{0,1}
和b=Point{1,1}
。则a<b
、b<a
和a==b
都不是真的,这使得算子不是可能点集上的排序。为了纠正这一点,你需要将其中一个维度(比如x)作为比较中的"主要"维度:
bool operator<(const Point &other) const
{
return ((this->x < other.x) ||
((this->x == other.x) && (this->y < other.y));
};
相关文章:
- 如何在 C# 中映射双 C 结构指针?
- 如何在C++中使用结构生成映射
- C++匿名结构作为std::映射值
- 添加静态constexpr成员是否会更改结构/类的内存映射
- C++:映射结构中的结构指针
- 无法添加多个键以映射将结构作为键
- 如何在 c++ 中创建结构向量的映射
- 从另一个 cpp 文件更改结构内、映射键内的变量
- 在映射中使用结构作为键,忽略 == 运算符,误报
- 用于对项目进行分组并将单个项目映射到其他组成员的数据结构
- 使用结构和映射创建priority_queue
- 在无序映射的结构化绑定中推导类型
- 如何将带指针的结构插入到映射中
- C++调用存储在映射结构中的函数指针
- 映射结构也支持排序
- 它无法将 c++ 映射结构编译为 map<A、pair<B、C> >
- 非易失性C++映射结构的备份方案
- 内存映射文件-映射结构而不是文件
- 无法推送到由静态映射<结构创建的队列,队列>
- 将映射结构强制转换为void指针和解引用