a vector is not an array -- you can use .size() if you want to know how many things are in it.
yes, the range based for loop syntax is a short hand of sorts.
It is really more like a form of pointer based loops, eg
something *sp = somestartposition;
for(; sp != someENDposition; sp++)
*sp.modify(value);
Although I have been studying recursion daily for the past week, I'm still find it challenging how to write recursive codes.
|
This is a difficult topic, and takes more than a week to absorb fully. Sure, simple functions are easy, but give it more time. Take a bit of time off and do some other learning, let this sit in your brain. Your brain is amazing, and it likes to work on understanding things 'offline'. After a break circle back and you may find it easier.
recursion, at the end of the function (tail-recursion) is equal to iterative code: the compiler knows how to rewrite this as a simple loop. If you do the recursion elsewhere in the function, it actually makes the function calls, which can be inefficient and can risk blowing out the call stack.
recursion does one thing, really. It provides you with a free stack data structure that you can use in creative ways without needing extra code. That gives you 2 main reasons to write recursive code, both of them relatively rare (one, using the free stack, and two, expressing an idea that is naturally recursive or that lends itself to significantly smaller code with recursion) and the third reason -- you like doing it or something, and use it when not necessary or helpful.
an example of a natural problem would be a recursive sequence, like factorials or fibonacchi, where a term is defined by the previous term(s). An example of example of using the stack is a maze solver, where if you get to a dead end, you pop back to the last decision and try another path. An example of not necessary is again a small (fit in int 64) factorial, which in real code would be a lookup table, not a computation of any kind.
Recursion as the best choice is rare. I would say < 10% of all problems fall into the 'don't need it, and even if could be done that way there is no reason to do so' category. Of that 10%, the vast (80%+) majority of those are very simple, one liners. The rest are where it is super useful and powerful, like array sorting. And of those, the majority again will be things that are been-there, done-that well known algorithms or following the pattern of one of those. A totally new problem with a new algorithm using recursion is a very rare thing. If you understand the recursion of sorting, tree processing, sequence generation, maze tracking, and maybe one or two advanced problems like 8 queens, you will be in really good shape.