Mostly in response to simple Zeds recursion ...
Why is recursion considered better than iteration? Especially in C ++. What happened with...
int myPow (int x, int p) { int i = 1; for (int j = 1; j <= p; j++) i *= x; return i; }
I am not saying that your answer is incorrect or somehow worse - itβs just that I got the impression that you think it is good, because it is recursive. IMO, especially in C ++, that biasing can lead to slow and even broken programs. Slow programs because you grow a huge stack, causing cache and virtual memory. Broken programs because you get a stack overflow where an iterative solution will work.
Some will look at your answer and consider the tail recursive and in any case will be optimized for iteration. Of course, this is not so - after the exit of each recursive call, there are many more times to do it, so it is not tail recursive. The fact is that in C ++ there are many more subtle things that prevent tail recursion optimization - even if the compiler does them at all. For example...
void myrecurse (plan *p) { plan i; i.prev = p;
In this case, all instances of the "plan" should remain on the stack. Therefore, stack frames cannot be discarded. Therefore, this is not optimized in the iteration, although after a recursive call exactly zero operations are performed. Not even hidden operations, such as cleaning destructors, since it is assumed that the plan is a POD structure.
By the way, this is based on what I did in real code - the data structure operation, which was planned during the recursion, but nothing changes in the source nodes until the recursion reaches the root / sheet, all the necessary new nodes were successfully distributed All locks have been acquired and there are no changes to get worse. At this point, iteration is performed through a linked list of plan instances to commit changes β the logic was more clear as an iteration than broken down into fragments related to the deployment of recursive calls.
Here, obviously, one should not say that recursion is automatically bad. It just makes me nervous when people seem to think that recursion is better than default iteration.