以struct作为键的映射返回不正确的值

map with struct as key returns incorrect value

本文关键字:映射 返回 不正确 struct      更新时间:2023-10-16

我有

struct data_cell{
    int owner;
    std::vector<int> shares;
};
data_cell** data; //grid, very big
std::map<data_cell, data_cell*> cells; //all uniq cells
bool operator==(const data_cell &b, const data_cell &o) {
    return (b.owner == o.owner && b.shares == o.shares);
}
bool operator<(const data_cell &b, const data_cell &o) {
    return (b.owner < o.owner && b.shares != o.shares);
}
int to_grid(float, float);

有时当我这样做的时候:

for (int i=0;i<ids.size();i++){//example
    data_cell o=ids[i];
    //some work where fills o.shares
    data[to_grid(x,y)]=(cells[o]?:cells[o]=(new data_cell(o)));
    printf("%d |%d|%d|%d %dn", s.id, o.owner, cells[o]->owner, data[to_grid(x,y)]->owner, to_grid(x,y));
}

我得到了。owner != cells[o]->owner, (printf显示不同的值),如果我在赋值前打印cells[o]它返回非零指针,但是这个键在map中不存在

我使用gcc-4.6.

这段代码有什么问题?

Add1:改为

bool operator<(const data_cell &b, const data_cell &o) {
    return (b.owner < o.owner && b.shares < o.shares);
}

没有帮助,但是

bool operator<(const data_cell &b, const data_cell &o) {
    return (b.owner < o.owner && b.shares <= o.shares);
}

Add2:最后一个可用的版本(我希望):

bool operator<(const data_cell &b, const data_cell &o) {
    return (b.owner < o.owner && b.shares <= o.shares) ||
            (b.owner <= o.owner && b.shares < o.shares);
}

可以添加一些内容吗?

您的==<操作符必须使a < b, a == bb < a中的一个是true,另外两个是false。由于operator<在您的实现中的b.shares != o.shares,这里的情况并非如此。