Question:
C++ Question?
Eugene
2006-12-06 19:32:54 UTC
Hello, I need a help. I have an array of structs and I need to make a reverse order of this array? How to do it? How to make all data in the array to be reversed?
Five answers:
RGB_Mars
2006-12-06 19:38:56 UTC
Do you have an array of structs, or an array of pointers to structs?



In the former, you'll need to loop over the array copying the 1st struct to a temporary variable, copy the last struct over top of the first, copy the temporary to the last...then repeat with the 2nd and the second last, then the 3rd and the third last, etc...



In the latter, you do the same as above but simply have to copy pointer locations instead of copying entire structs (much, MUCH more efficient).
Yoda Miyagi
2006-12-07 04:06:58 UTC
what an inneficient thing to do !

First the c++ way would have to use a std::vector.

Second, what is the point of reversing an array? Simply read it backward



But if for some really strange reason, you really need to to this. Use a std::stack Make sure your struct has an assignent operator and read your array from begin to end, pushing each of them on the stack as you go. Once you're done. Pop each of the value from the stack and assign them to the array once again from beginning to end.
VzjrZ
2006-12-07 03:37:00 UTC
use a loop, and copy everything from the array into a temp array and then copy it back in the reverse order...
Santosh
2006-12-07 03:45:14 UTC
Node *Reverse (Node *p)

{

Node *pr = NULL;

while (p != NULL)

{

Node *tmp = p->next;

p->next = pr;

pr = p;

p = tmp;

}

return pr;

}
yang
2006-12-07 03:43:05 UTC
use looping in your program


This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.
Loading...