I think at this point [after push_back
] reference variable current_node
becomes invalid, because the vector
is just reallocated. Am I correct?
Yes, you are correct. The vector
may or may not be reallocated, but since there is a possibility, you should consider the prior reference invalidated.
What's the way around of this problem ?
If you pre-allocated enough elements upfront, or use a plain C array instead of a vector, the reference would remain valid. You must ensure that the capacity is sufficient for the worst-case scenario to run without re-allocations.
If you always access the elements sequentially, another solution could be using a linked list, because adding elements to a linked list do not change references to its existing elements.