繁体   English   中英

能够从 stl 遍历 c++ map,但无法分配值或打印出 ZA2F2ED4F8EBC04614C21A2DDC 变量

[英]Able to iterate through c++ map from stl, but unable to asign values or print out class variables

我目前正在尝试使用 c++ stl 提供的 map。 我的键值对都是指向自定义 object 的指针。 我能够将数据存储到 map 中,并且还成功地遍历了 map 的所有键和值。 但是,每当我尝试通过其键访问 map 中的值成员变量之一时,我都会收到以下运行时错误:

分段错误(核心转储)

我正在为 map 使用自定义比较器。 我相信这就是问题所在。 我相信这是因为每当我在没有自定义比较器的情况下运行代码时,错误就会消失。

请注意,Eigen 库的使用仅用于线性代数目的。 请尝试在示例代码中查看它,因为它只是在我的特定实现中用于我试图解决的问题。

请使用以下代码作为上下文:

 #include <iostream> #include <map> #include <Eigen/Dense> #include <vector> #include "A_star.h" using namespace std; struct NodeCostPointer { bool operator()(star::Node* const& a,star::Node* const& b){ return a->f_cost >= b->f_cost; int main() { Eigen::Matrix<float,3,3> obj; obj(0,0) = 3360; obj(1,0) = 3360; obj(2,0) = 3360; obj(0,1) = 7000; obj(1,1) = 7000; obj(2,1) = 7000; obj(0,2) = 5280; obj(1,2) = 5280; obj(2,2) = 5280; Eigen::Matrix<float,3,1> end; end(0) = 12300; end(1) = 12300; end(2) = 12300; Eigen::Matrix<float,3,1> start; start(0) = -.8; start(1) = -.8; start(2) = -.8; map<star::Node*,star::Node*, NodeCostPointer> test; star::Node* nodetest = new star::Node(start,6,0); star::Node* nodetest2 = new star::Node(end,6,0); star::Node* nodetest3 = new star::Node(start,5,std::numeric_limits<float>::infinity()); test[nodetest] = nodetest3; test[nodetest2] = nodetest3; // error occurs here: cout << test[nodetest]->f_cost << endl; // or test[nodetest]->f_cost = 4; map<star::Node*,star::Node*,NodeCostPointer>::iterator itt; for(itt=test.begin();itt.=test;end();itt++){ cout << itt->first->cordinates << endl; cout << " \n"; } return 0

节点class的实现:

 star::Node::Node(Eigen::Matrix<float,3,1> _cordinates, float _h_cost, float _g_cost): cordinates {_cordinates}, h_cost {_h_cost}, g_cost {_g_cost}{ f_cost = h_cost+g_cost; obstical = false; closedNode = false; };

感谢@timl 和其他人为我指出正确的方向。 问题是由于不满足严格的弱排序要求进行比较。 将比较器更改为以下内容似乎使一切正常:

 struct NodeCostPointer { bool operator()(star::Node* const& a,star::Node* const& b){ return std::tie(a->f_cost,a->h_cost,a->cordinates(0)) < std::tie(b->f_cost,b->h_cost,b->cordinates(0)); }

在了解了这种表示法的工作原理后,我决定添加额外的东西进行比较,即 h_cost 和坐标。 但是,不包括它们当然也可以。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM