I have a class that is a delegate to a container and internally stores an iterator to this container.
class A {
public:
list<int> m_data;
list<int>::iterator m_relevantDataStart;
A(const A & cpy) {
m_data = cpy.m_data;
m_relevantDataStart = cpy.m_relevantDataStart; //<--- UNWISE
}
};
Now the problem is that if I try to write a simple constructor for copying both container and iterator as depicted above, the iterator becomes unusable in the context of the copy, more specifically, I later encounter a runtime exception when trying to perform comparison:
`if(m_relevantDataStart == m_data.begin())` - Expression: list iterators incompatible
This I presume arises because the m_relevantDataStart
is still an iterator of m_data
of the class I copied from, whereas m_data.begin()
points to a copy of the original container.
I found this answer, which appears to be of some relevance, implying that the iterator
pointing to the original container would indeed be unusable.
My question and TL;DR: Is there a way to mirror an iterator to original container such that the result of this "mirroring" would point to the corresponding element in the copy container?
I could think of one solution which would require determining items index in the original container (linear complexity when dealing with std::list
) and advancing an iterator in the copy container, but unless I used some random-access container instead of std::list
it appears to be quite inefficient.
There's also always the option of writing a custom container copying algorithm, which I would really like to avoid.