STL映射迭代器运行时错误

时间:2012-06-25 07:52:29

标签: c++ map iterator runtime

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

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 变量时,迭代器就会失效。指向内存的指针仍然存在(我在调试器中检查过),但迭代器的内容会破坏(未引用的变量)。

我做错了什么?

更多代码:

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

1 个答案:

答案 0 :(得分:3)

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

(迭代器具有值语义,并且极少数情况下 你想要一个迭代器的引用 - 然后几乎总是 作为参数。)