如何處理成員函數中的遞歸? [英] How to handle recursion in member functions?

查看:0
本文介紹了如何處理成員函數中的遞歸?的處理方法,對大家解決問題具有一定的參考價值,需要的朋友們下面隨著小編來一起學習吧!

問題描述

例如,我有一個empty函數來清除鏈表:

void empty(Node* head) {
        if (head->next) { empty(head->next); }
        delete head;
        head = nullptr;
    }

但后來我為鏈表創建了一個類,所以現在不需要傳遞head參數:

void empty() {
        if (head->next) { empty(head->next); }
        delete head;
        head = nullptr;
    }

但是empty(head->next)行顯然是錯誤的,因為empty不接受任何參數。我的想法是在函數中創建一個函數(使用lambda),類似于:

void empty() {
        std::function<void(Node*)> emptyWrapper = [&] (Node* l_head) {
            if (l_head->next) { emptyWrapper(l_head->next); }
            delete l_head;
            l_head = nullptr;
        };
        emptyWrapper(head);
    }

但我想知道有沒有更好的辦法。最近,Lambdas對我來說是一種理想的固定方式。

推薦答案

一般方法是聲明公共成員函數,該成員函數又調用私有靜態遞歸成員函數。

請注意,名稱empty聽起來令人困惑。最好將函數命名為clear。

給您

#include <functional>

//...

class List
{
public:
    //...
    void clear() 
    {
        clear( head );
    }

private:
    static void clear( Node * &head )
    {
        if ( head )
        {
            delete std::exchange( head, head->next );
            clear( head ); 
        }
    }
    //...
}

無需定義輔助靜態函數即可使用相同的方法。

void clear()
{
    if ( head )
    {
        delete std::exchange( head, head->next );
        clear();
    }
}

這里是一個演示程序。

#include <iostream>
#include <iomanip>
#include <functional>

template <typename T>
class List
{
private:
    struct Node
    {
        T data;
        Node *next;
    } *head = nullptr;

public:
    void push_front( const T &data )
    {
        head = new Node { data, head };
    }

    friend std::ostream & operator <<( std::ostream &os, const List &list )
    {
        for ( Node *current = list.head; current; current = current->next )
        {
            os << current->data << " -> ";
        }

        return os << "null";
    }

    bool empty() const { return head== nullptr; }

    void clear()
    {
        if ( head )
        {
            delete std::exchange( head, head->next );
            clear();
        }
    }
};

int main() 
{
    List<int> list;

    const int N = 10;

    for ( int i = N; i != 0; )
    {
        list.push_front( i-- );
    }

    std::cout << list << '
';

    list.clear();

    std::cout << "list is empty " << std::boolalpha << list.empty() << '
';

    return 0;
}

程序輸出為

1 -> 2 -> 3 -> 4 -> 5 -> 6 -> 7 -> 8 -> 9 -> 10 -> null
list is empty true

這篇關于如何處理成員函數中的遞歸?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持IT屋!

查看全文
登錄 關閉
掃碼關注1秒登錄
發送“驗證碼”獲取 | 15天全站免登陸
全免费A级毛片免费看无码播放