【问题标题】:STL map iterator runtime errorSTL 映射迭代器运行时错误
【发布时间】:2012-06-25 07:52:29
【问题描述】:

我需要帮助解决一个奇怪的运行时错误。这是给出它的代码:

JacobianCol &diag_index_column = J[diag_index];
JacobianColData::iterator &diagonal_element = diag_index_column.find(diag_index);
Jacobian J2 = J; //added to reveal the problem
J[diag_index].divide_by(diagonal_element);

我想要什么。我想保存迭代器 diagonal_element 并将其传递给 divide_by 函数。但是当我调用 J 变量时,迭代器会下降。指向内存的指针仍然存在(我已在调试器中检查过),但迭代器的内容已损坏(未引用的变量)。

我做错了什么?

更多代码:

雅可比 J:

class Jacobian
{
private:
   std::vector<JacobianCol> _J;
...
public: 
...
   JacobianCol& operator [](int i); //return _J[i];
};

JacobianCol:

typedef std::map<int, Submatrix> JacobianColData;

class JacobianCol
{
private:
...
 JacobianColData _col_data;
public:
...
 JacobianColData::iterator &find(int key, bool need_append = false);
};

寻找实施:

JacobianColData::iterator &JacobianCol::find(int key, bool need_append)
{
 if(need_append)
  this->insert(key);
 JacobianColData::iterator &res = this->_col_data.find(key);
 return res;
}

【问题讨论】:

  • 如果this-&gt;_col_data.find(key); 返回end() 怎么办?如果调用者取消引用它,它会导致未定义的行为。

标签: c++ map iterator runtime


【解决方案1】:

您的代码甚至无法使用像样的编译器进行编译。 diagonal_element 不应该是参考,而是价值。你不能初始化一个 临时参考。

(迭代器具有值语义,而且很少有这种情况 你想要一个迭代器的引用——然后几乎总是 作为参数。)

【讨论】:

  • 谢谢你,詹姆斯·坎泽。它有帮助
猜你喜欢
  • 2011-04-02
  • 1970-01-01
  • 2011-05-29
  • 1970-01-01
  • 2011-05-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多