2011-01-13 69 views
2

我在这里有一个递归的函数,但我反而想让它不递归。我只是不知道如何。使这个函数不递归?

void AguiWidgetManager::recursiveRender(const AguiWidget *root) 
{ 
    //recursively calls itself to render widgets from back to front 
    AguiWidget* nonConstRoot = (AguiWidget*)root; 
    if(!nonConstRoot->isVisable()) 
    { 
     return; 
    } 

     clip(nonConstRoot); 

     nonConstRoot->paint(AguiPaintEventArgs(true,graphicsContext)); 

     for(std::vector<AguiWidget*>::const_iterator it = 
      root->getPrivateChildBeginIterator(); 
      it != root->getPrivateChildEndIterator(); ++it) 
     { 
      recursiveRender(*it); 
     } 
     for(std::vector<AguiWidget*>::const_iterator it = 
      root->getChildBeginIterator(); 
      it != root->getChildEndIterator(); ++it) 
     { 
      recursiveRender(*it); 
     } 

} 

它可以,如果解决方案不会使用迭代器。

感谢

+6

你知道,如果你使这个函数非递归,它将会被命名得很差。 – 2011-01-13 03:40:32

+0

请问为什么?我认为递归可能是最简单的方法。迭代解决方案可能会使用堆栈并手动实现递归。另外,`std :: for_each(root-> getChildBeginIterator(),root-> getChildEndIterator(),recursiveRender);`看起来比你拥有的更好。 – 2011-01-13 03:44:55

+0

@Chris Lutz`for_each`可能看起来更好,但除非我错误,因为函数是成员函数,所以需要`mem_fun_ref`活页夹或类似的东西来使它调用正确。 – 2011-01-13 04:00:49

回答

6

最简单的办法就是保持自己的堆栈。 Psuedoish示例代码:

stack s; 
while(!s.empty()) 
{ 
    root = s.pop(); 

    //your code here 
    //replace each recursive call with s.push(it) 
} 

此外,抛弃constness是一个糟糕的主意。如果你想修改它,它首先不应该是一个常量参数。

1

一般情况下,你就需要自己实现堆栈:

clear stack 
push first item onto stack 
while stack is not empty: 
    pop top item off stack 
    do action for item (clip, paint) 
    push children onto stack (if any)