gpt4 book ai didi

c++ - 以结构为键的映射返回不正确的值

转载 作者:行者123 更新时间:2023-11-28 00:00:54 25 4
gpt4 key购买 nike

我有

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]->owner,(printf 显示不同的值),如果我在分配之前打印 cells[o],它会返回非零指针,但 map 中不存在这个键.

我使用 gcc-4.6。

这段代码有什么问题?

添加 1:改成

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

添加 2:最后一个有效的版本(我希望):

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 == b , 和 b < atrue , 和另外两个 false .由于b.shares != o.shares,这里不是这种情况在你执行operator< .

关于c++ - 以结构为键的映射返回不正确的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39023102/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com