1

我有一组数组,每个数组 ( data[]) 都存储在一个双向链表节点ArrayNode中。我从数组中的某个给定索引开始,然后迭代到另一个数组中的另一个索引(它们可能是同一个数组)。我确定我的两个节点是链接的,并且第一个节点位于第二个节点的“左侧”。

struct ArrayNode
{
 ArrayNode* prev;
 ArrayNode* next;

 int data[16];
 unsigned int count;
};



void iterate(ArrayNode* startnode, unsigned int startposition, ArrayNode* endnode, unsigned int endposition)
{
 for (unsigned int index = startposition; index < startnode->count; ++index)
 {
  std::cout << startnode->data[index] << "\n"; //I'd do some processing here
 }

 for (ArrayNode* node = startnode->next; node != endnode; node = node->next)
 {
  for (unsigned int index = 0; index < node->count; ++index)
  {
   std::cout << node->data[index] << "\n"; //I'd do some processing here
  }
 }

 for (unsigned int index = 0; index < endposition; ++index)
 {
  std::cout << endnode->data[index] << "\n"; //I'd do some processing here
 }
}

上面的代码在几个方面存在缺陷。首先,如果startnode == endnode,它会给出不正确的输出。其次,拥有 3 个循环对于维护和代码大小来说是低效的。似乎应该可以让中间嵌套循环优雅地处理所有情况,但我不知道如何。是吗?如果没有,应该怎么做?

如果可能的话,我想避免为此创建一个迭代器对象。

4

3 回答 3

1

这样的东西适合您的需要吗?

ArrayNode* curnode = startnode;
unsigned int curposition = startposition;
while ((curnode != endnode) || (curposition != endposition)) {
        std::cout << curnode->data[curposition] << std::endl;
        if (++curposition == curnode->count) {
                curnode = curnode->next;
                curposition = 0;
        }
}

请注意没有错误检查,这留给读者作为练习。

于 2013-01-11T15:30:04.600 回答
1

这应该有效:

void iterate(ArrayNode* startnode, unsigned int startposition, ArrayNode* endnode, unsigned int endposition)
{
  ArrayNode* node = startnode;
  unisgned int pos = startposition;
  while (!(node == endnode && pos == endposition)) {
    process(node->data[pos]);
    ++pos;
    if (pos == node->count) {
      pos = 0;
      node = node->next;
    }
  }
}
于 2013-01-11T15:30:27.793 回答
0

我认为这会做你想做的,但我认为它并没有更清晰、更短、更快或更容易维护。如果是我,我会使用您在原始帖子中的代码并清楚地评论它。

void iterate(ArrayNode* startnode, unsigned int startposition, ArrayNode* endnode, unsigned int endposition)
{
    int startindex = startposition;
    for (ArrayNode* node = startnode; node != NULL; node = node->next)
    {
        int endindex = ( node == endnode ) ? endposition : node->count;
        for (unsigned int index = startindex; index < endindex; ++index)
        {
            std::cout << node->data[index] << "\n"; //I'd do some processing here
        }
        startindex = 0;
        if ( node == endnode ) 
            break;
    }
}
于 2013-01-11T15:29:38.050 回答