使用struct作为键的map返回不正确的值

时间:2016-08-18 16:19:19

标签: c++

我有

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 %d\n", s.id, o.owner, cells[o]->owner, data[to_grid(x,y)]->owner, to_grid(x,y));
}

我得到o.owner!= cells [o] - &gt; owner,(printf显示不同的值),如果我在分配之前打印单元格[o]则返回非零指针,但此键不存在于地图。

我使用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);
}

可能会有一些补充吗?

1 个答案:

答案 0 :(得分:3)

您的==<运营商必须满足a < ba == bb < a true之一,并且另外两个false。由于您在b.shares != o.shares的实施中operator<,因此情况并非如此。