STL 映射迭代器运行时错误



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

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

雅各比安科尔:

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

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

(迭代器具有值语义,并且非常非常少的情况您希望引用迭代器的位置 - 然后几乎总是作为参数。

最新更新