Array PopFront Method C++

后端 未结 5 2032
说谎
说谎 2021-01-29 15:48

Trying not to lose it here. As you can see below I have assigned intFrontPtr to point to the first cell in the array. And intBackPtr to point to the last cell in the array...:

5条回答
  •  攒了一身酷
    2021-01-29 16:15

    The original question seems to be that you don't understand why the function popFront returns 3 times when there are 3 elements?

    If that's the case, I think you are missing the point of recursion.

    When you make a recursive call, you are calling the same function again, basically creating a new stack frame and jumping back to the same function. So if there are 3 elements, it will recurse by encountering the first element, encountering the second element, encountering the third element, returning from the third encounter, returning from the second encounter, and returning from the first encounter (assuming you are properly consuming your array, which you don't appear to be).

    The current function cannot return until the recursive call has iterated, thus it may appear to return from the last element before the second, and the second before the first.

    That is how recursion works.

    I wasn't able to make sense of your example, so I whipped one up real fast:

    #include 
    
    using namespace std;
    
    bool popfront(int* ptr_, int* back_) {
        cerr << ptr_[0] << endl;
        if(ptr_ != back_) {
            popfront(++ptr_, back_);
        }
        return true;
    }
    
    int main() {
       int ar[4] = {4,3,2,1};
       popfront(ar, ar + 3);
       return 0;
    }
    

    That's not great, but it should get the point across.

提交回复
热议问题