gpt4 book ai didi

c++ - 链表的 Lambda 长度

转载 作者:行者123 更新时间:2023-11-30 03:40:57 26 4
gpt4 key购买 nike

考虑以下链表节点的定义:

struct Node
{
int data;
struct Node *next;
};

我是 C++ 的新手,来自函数式编程。我想写一个 lambda 来计算链表的长度。我写道:

auto listLength = [](Node * list){
if(list == NULL) return 0;
else return 1 + listLength(list -> next);
};

error: variable 'lengthList' declared with 'auto' type cannot appear in its own initializer

如果我从 auto 更改为 int 我得到:

 error: called object type 'int' is not a function or function pointer

问题是什么?

最佳答案

问题是双重的:

1) lambda 需要捕获在 lambda 之外定义的任何对象。

2) listLength 的定义直到整个变量声明结束才完成。

这是一个先有鸡还是先有蛋的问题。最干净的解决方案是使用 std::function:

#include <functional>

std::function< int (Node *)> listLength;

listLength = [&](Node * list){
if(list == NULL) return 0;
else return 1 + listLength(list -> next);
};

关于c++ - 链表的 Lambda 长度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37646137/

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