[英]How to call a recursive linked list traversal function in C++
I have this function: 我有这个功能:
void TraverseRecursive ( Node * head, void (*visit) (Node *) )
{
if ( head != nullptr )
{
visit( head ) ;
TraverseRecursive( head->next, visit ) ;
}
}
And I'm trying to call it in main.cpp with 我正在尝试在main.cpp中使用
TraverseRecursive ( head, TraverseRecursive ) ;
Which gives me the error "argument of type "void (*)(Node *head, void (*visit)(Node ))" is incompatible with parameter of type "void ( )(Node *)" " 这给了我错误“类型为“ void(*)(Node * head,void(* visit)(Node ))的参数”与类型为“ void( )(Node *)的参数不兼容 ”的错误
So how do I correctly call it? 那么我该如何正确地称呼它呢? I am just learning linked lists and obviously don't understand what
我只是在学习链表,显然不明白
void (*visit) (Node *)
means at all. 意味着一切。
The second argument should be a function to call back for every node in the list. 第二个参数应为针对列表中的每个节点进行回调的函数。 It only takes a single parameter (the node to "visit").
它只需要一个参数(要“访问”的节点)。
void visitor(Node *node)
{
printf("%s\n", node->data); // Or whatever
}
TraverseRecursive( head, visitor ) ;
Side note: What wasteful use of recursion. 旁注:什么浪费使用递归。 If you're lucky, the compiler will optimize it away.
如果幸运的话,编译器会对其进行优化。 You should be using
您应该使用
void TraverseRecursive( Node * head, void (*visit) (Node *) )
{
for (; head != nullptr; head = head->next)
{
visit( head ) ;
}
}
void (*visit) (Node *)
means "pointer to a function taking one argument of type Node* and returning void". 表示“指向具有Node *类型的一个参数并返回void的函数的指针”。 But TraverseRecurive takes two argumenst and is therefore of different type.
但是TraverseRecurive需要两个参数,因此类型不同。 You need to define a function like
您需要定义一个像
void doSomething(Node* n)
{
}
and pass it to TraverseRecursive 并将其传递给TraverseRecursive
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.