gpt4 book ai didi

c++ - 如何处理成员函数中的递归?

转载 作者:行者123 更新时间:2023-12-02 09:21:23 24 4
gpt4 key购买 nike

例如,我有一个 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);
}

但是我想知道是否有更好的方法。 Lambda 最近成了我的固定想法。

最佳答案

一般方法是声明一个公共(public)成员函数,该函数又调用一个私有(private)静态递归成员函数。

请注意,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 << '\n';

list.clear();

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

return 0;
}

程序输出为

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

关于c++ - 如何处理成员函数中的递归?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61921720/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com