gpt4 book ai didi

c++ - 在哪种情况下,std::map 中的插入会失败?

转载 作者:行者123 更新时间:2023-11-30 03:30:11 24 4
gpt4 key购买 nike

在我的代码中有这些行:

if(mymap.count(plan) == 0) {
std::vector<XYZ> v;
v.reserve(10);
mymap.emplace(plan, v);
std::cout << "Plan " << plan.normal << " @ " << plan.O << " added";
}

//I inserted this code for debugging
std::map<Plan, std::vector<XYZ>>::const_iterator it = mymap.find(plan);
if(it == this->intersections.end())
std::cout << "not found";

我怎么可能在 plan addednot found 之后读取控制台?

我的 map 是这样声明的:

std::map<Plan, std::vector<XYZ>, PlanComp> mymap;

在某些时候我认为它来自比较器,但它尊重非自反性、反对称性、传递性、等价的传递性(根据 this blog 就足够了):

struct PlanComp {
bool operator()(const Plan& l, const Plan& n) const {
return (l.O.x != n.O.x) || (l.O.y != n.O.y) || (l.O.z != n.O.z)
|| (l.normal.x != n.normal.x) || (l.normal.y != n.normal.y) || (l.normal.z != n.normal.z);
}
};

struct XYZ {
double x;
double y;
double z;
};

struct Plan {
XYZ O;
XYZ plan;
};

最佳答案

您的比较器未定义 strict weak ordering (松散地说,“小于”定义元素顺序的语义)。因此,您的代码表现出未定义的行为。

最简单的解决方案是使用词典 比较器 - 比较 x先比较y仅在平局的情况下,依此类推。在 C++11 中,这更简单; operator < for tuples 已经为你做了这个(你可以使用 std::tie 来获取元组)。查看 Operator < and strict weak ordering 的答案例如。

关于c++ - 在哪种情况下,std::map 中的插入会失败?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45185278/

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