I have a set of arrays, with each array (data[]) stored in a doubly linked list node ArrayNode. I start at some given index in an array, and I iterate to another index in another array (they may be the same array). I know for sure that my two nodes are linked, and that the first is “to the left” of the second.
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
}
}
The above code is flawed in a couple ways. First of all, if startnode == endnode, it will give the incorrect output. Second, having 3 loops is inefficient for maintenance and code size. It seems like it should be possible to have the middle nested loop handle all cases elegantly, but I’m not seeing how. Is it? If not, how should this be done?
I want to avoid making an iterator object for this if possible.
This should work: