Denis Kharitonov
Denis Kharitonov

Reputation: 209

STL map iterator runtime error

I need help with a weird runtime error. Here's the code which gives it:

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

What I want. I want to save iterator diagonal_element and pass it to a divide_by function. But when I call J variable the iterator goes down. The pointer to the memory remains (I've checked that in debugger) but the content of the iterator corrupts (unreferenced variable).

What am I doing wrong?

Some more code:

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

find implementation:

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

Upvotes: 1

Views: 578

Answers (1)

James Kanze
James Kanze

Reputation: 153899

Your code won't even compile with a decent compiler. diagonal_element should not be a reference, but a value. You cannot initialize a reference with a temporary.

(Iterators have value semantics, and there are very, very few cases where you want a reference to an iterator—and then almost always as a parameter.)

Upvotes: 3

Related Questions