以struct作为键的映射返回不正确的值
map with struct as key returns incorrect value
我有
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 == b
和b < a
中的一个是true
,另外两个是false
。由于operator<
在您的实现中的b.shares != o.shares
,这里的情况并非如此。
相关文章:
- C++映射:具有自定义类的运算符[]不起作用(总是返回0)
- 如何在映射中返回null
- 从函数返回对映射的引用
- 为什么我不能返回带有透明函子的法线映射引用?
- CGAL-三角网格,返回面对面映射
- 返回各种类型的函数的SWIG类型映射
- 类型映射资源并将列表转换为矢量(并返回)
- 访问range_expression中的嵌套元素会返回不完整的映射(段错误)
- C++ 返回映射中对象的值
- 返回字符串和不同向量数据类型的映射C++
- 取消引用映射迭代器时返回对临时的引用
- 当请求的键丢失时,有没有办法从向量映射返回 std::vector ref?
- 为什么 unordered_map::equal_range upper_bound 如果键小于第一个映射元素,则返回
- 整数和元组的静态 STL 映射返回 0
- C++函数来返回基于参数的比较器通用映射类型?
- 无序映射返回NULL值
- Rcpp映射返回
- 如何从新插入的对(到映射)返回引用对
- 以struct作为键的映射返回不正确的值
- C++映射返回基于变量键的类对象