You are storing pointers to other nodes in the vector. When you make a copy of it the new nodes still point to the nodes in the original vector. Specifically the pointers you have in next_node_list
and previous_node
.
If you pass sub by reference it might start working. However, it is generally unsafe to store pointers into dynamic containers. When elements get added and removed from vectors they can move from their original location in memory. If you remove from the front then all the remaining elements get shuffled forward. When using push_back there might not be enough space left so a new allocation might be made and the elements are copied/moved to an entirely new block of memory.
One thing you could try is to use a std::vector<std::shared_ptr<node>>
and instead of using raw node pointers in next_node_list
and previous_node
, make them std::weak_ptr<node>
. That will allow you to shuffle the vector around whilst maintaining the integrity of the connections.