What's the best way of iterating through multiple lists of different sizes simultaneously in C++ using iterators?

StackOverflow https://stackoverflow.com/questions/23338588

سؤال

I'm using std::list to create my lists. Each item in the linked list contains a linked list of char. Each list can have a different number of chars.

I want to iterate through 3 elements of the list at a time using an iterator for each list. When I'm iterating through it I want to be moving along the full length of the middle line and checking the char in the line above and below at the same time.

e.g. if the following are the contents of my linked list of linked list of char,

  1. abcdef
  2. the quick brown fox
  3. zxy

I want to be iterating through the 2nd list (middle) and checking the above and below characters. e.g. t - a is upper and z is lower, h - b is upper and x is lower, etc. The problem is when list 3 and 1 stop and I still want to iterate through to the end of list 2 without getting errors for lists 1 and 3 finishing.

I'm not too sure how to go about this as I originally had a for loop for my middle list and was manually incrementing the upper and lower lists but ran into some issues when the upper or lower lists had a smaller number of elements than my middle list did.

e.g. I had something like this:

list<char>::const_iterator i, u, l
u = upper_row.begin();
l = lower_row.begin();
for (i = middle_row.begin(); i != middle_row.end(); i++) 
{
  // code to do something with upper, middle and lower lists
  u++;
  l++
}
هل كانت مفيدة؟

المحلول

Check if the list iterators for upper/lower have reached the end. Then change your logic accordingly such that it can work for the cases when lower or upper are not present.

list<char>::const_iterator i, u, l
u = upper_row.begin();
l = lower_row.begin();
for (i = middle_row.begin(); i != middle_row.end(); ++i) 
{
  bool has_upper = (u != upper_row.end());
  bool has_lower = (l != lower_row.end());
  // code to do something with upper, middle and lower lists
  // >> only do something with upper/lower if has_upper/has_lower is true
  if(has_upper) ++u;
  if(has_lower) ++l;
}

Additional note: always use ++i for iterators, not i++!

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top