How to implement this function so that the vector can be passed backto the calling function?

X

xz

I wrote a function which looks like:

bool Xxx::findShortestPath(int xS, int yS, int xT, int yT,
vector<Vertex*> path) {
....
}

It meant to find a path, save the path in vector<Vertex*> path, and
pass the path back to the calling function.

And in some other function (say, main()), I called this function like:

int main() {
....
vector<Vertex*> path;
xxx.findShortestPath(0, 0, 9, 9, path);
// then print out the path
}


However, I just noticed that it failed to passed the path to the
main() function. That is, in the function findShortestPath(...), the
data has been loaded into *path*, but when it goes back to main(), all
data is lost.
I know this happens because of the memory management logic, but I am
not clear about how to fix this and get what I want.
Anybody gives some hints?
Thanks a lot!
 
K

Kai-Uwe Bux

xz said:
I wrote a function which looks like:

bool Xxx::findShortestPath(int xS, int yS, int xT, int yT,
vector<Vertex*> path) {
...
}

It meant to find a path, save the path in vector<Vertex*> path, and
pass the path back to the calling function.

And in some other function (say, main()), I called this function like:

int main() {
...
vector<Vertex*> path;
xxx.findShortestPath(0, 0, 9, 9, path);
// then print out the path
}


However, I just noticed that it failed to passed the path to the
main() function. That is, in the function findShortestPath(...), the
data has been loaded into *path*, but when it goes back to main(), all
data is lost.

Make the signature:

bool Xxx::findShortestPath(int xS, int yS, int xT, int yT,
I know this happens because of the memory management logic, but I am
not clear about how to fix this and get what I want.

It happens because you did "pass by value" not "pass by reference".



Best

Kai-Uwe Bux
 
J

James Kanze

Make the signature:
bool Xxx::findShortestPath(int xS, int yS, int xT, int yT,
vector<Vertex*> & path);
^^^

From a purely conceptual point of view, something like:

Fallible< std::vector< Vertex* > >
Xxx::findShortestPath( ... ) ;

would be better. In practice, if you call the function a lot,
and the paths tend to be fairly large, the performance
implications may become an issue.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,015
Latest member
AmbrosePal

Latest Threads

Top