How to not change original array values when using recursive function in C++?

I am using a function to change the array's elements. Basically, it merges two elements and puts them to the first element of the array and returns it. After that, I am calling a recursive function and it works until there is one element left in the array. However, when I want to go back on the recursive function it seems that my array is not going back to its old form as well. I tried to send them by reference and value, but still, the first element is not corrected when I want to go back from recursive. What can I do?
Armanc wrote:
What can I do?

Post your code.
I solved it! I just put a template array inside my function and every time I did operations on that array to save the original values. Thank you!
Aarrgh! That's the worst way to solve it!

What that does is create a new function for every recursion point...

...except those recursion points you are unlucky enough to have perfectly match a previous recursion point.

Your code is brittle beyond expectations.

The correct way to handle changes is to simply undo them when the recursive call needs to return as a backtrace.

Anything you do recursively to that array you can undo in the same step. This maintains the array's stability requirement between recursive calls.

Simply duplicating the array with each recursive call is expensive -- especially when you have the compiler doing the work for you to create new code for each step.

If you turn the assignment in as-is, you should expect to get low marks. You need to fix it properly.

Hope this helps.
Topic archived. No new replies allowed.