2013-01-11 22 views
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個迴路對於維護和代碼大小而言效率低下。看起來應該可以讓中間的嵌套循環處理所有的案例,但我沒有看到如何。是嗎?如果不是,應該怎麼做?

我想避免爲此做一個迭代器對象,如果可能的話。

+0

爲什麼你的arent使用你的對象更加自然的表示?例如'std :: deque'以類似的方式存儲數據,就像你的特別黑客一樣。然後你得到迭代器和高級抽象的所有優點。你真的**需要**迭代一些抽象,就像你的例子清楚地表明的那樣。 – pmr

+0

因爲我需要以deque不公開的方式訪問內部。我最終可能會使用deque或它的擴展,但使用這個非常簡單的手動滾動數據結構可以更容易地找出「我在做什麼」。 – user173342

回答

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; 
    } 
    } 
} 
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; 
    } 
} 
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; 
     } 
} 

請注意,沒有錯誤檢查,這是作爲讀者的練習。

+1

你想在'while'條件下使用'||'。 – Angew

+0

對吧。固定。 –

相關問題