Damir
Damir

Reputation: 56199

Replace elements in list from element with value to end with new list

I have path in board like list of pairs of indexes like

list<pair<int,int> > *path;

When character reaches obstacle I need to replace in path all from current position to end with new path but to save path from start to obstacle same ( to clarify a little character has start and destination cell and moves from start to destination and back and repeat again same. To avoid lot off calculation I would try to save part of path without obstacle and just replace old part with new from obstacle to end). Is there easy way to do this without iterating ?

Edited later to clarify: path old is [(0,0),(0,1),(1,1),(1,2),(1,3),(1,4)] and obstacle is on cell (1,2) so character goes [(0,0),(0,1),(1,1)] searches for new path which is for example [(1,1),(2,1),(2,2),(1,3),(1,4)] so I need to replace from old path (1,1),(1,2),(1,3),(1,4) with (1,1),(2,1),(2,2),(1,3),(1,4)

Upvotes: 1

Views: 541

Answers (1)

us2012
us2012

Reputation: 16253

If I understand your question correctly: You have a list path from start to destination, which hits an obstacle somewhere in the middle (you have to know where, so let's say you have a valid list<...>::iterator obstacle that points to the obstacle). You also have a newpath going from *(obstacle - 1) to destination, and you want to cut and paste those two paths together. This is how you could do it (I'm assuming lists instead of list*s here, but if you really need that you can easily rewrite it to work with the pointer):

//kill the wrong bit of the old path
path.erase(obstacle, path.end());
//append the correct newpath
path.splice(path.end(), newpath, newpath.begin(), newpath.end());

Note that newpath is empty after this operation.

Upvotes: 2

Related Questions