C++: Loop Over Multiple Arrays Simultaneously

Bjarne-stroustrup
 


Loop over multiple arrays (or lists or tuples or whatever they’re called in your language) and print the ith element of each. Use your language’s “for each” loop if it has one, otherwise iterate through the collection in order with some other loop.

For this example, loop over the arrays (a,b,c), (A,B,C) and (1,2,3) to produce the output

aA1
bB2
cC3

If possible, also describe what happens when the arrays are of different lengths.

With std::vectors:

#include <iostream>
#include <vector>
 
int main(int argc, char* argv[])
{
   std::vector<char> ls(3); ls[0] = 'a'; ls[1] = 'b'; ls[2] = 'c';
   std::vector<char> us(3); us[0] = 'A'; us[1] = 'B'; us[2] = 'C';
   std::vector<int> ns(3);  ns[0] = 1;   ns[1] = 2;   ns[2] = 3;
 
   std::vector<char>::const_iterator lIt = ls.begin();
   std::vector<char>::const_iterator uIt = us.begin();
   std::vector<int>::const_iterator nIt = ns.begin();
   for(; lIt != ls.end() && uIt != us.end() && nIt != ns.end();
       ++lIt, ++uIt, ++nIt)
   {
      std::cout << *lIt << *uIt << *nIt << "\n";
   }
}

Using static arrays:

#include <iostream>
 
int main(int argc, char* argv[])
{
   char ls[] = {'a', 'b', 'c'};
   char us[] = {'A', 'B', 'C'};
   int ns[] = {1, 2, 3};
 
   for(size_t li = 0, ui = 0, ni = 0;
       li < sizeof(ls) && ui < sizeof(us) && ni < sizeof(ns) / sizeof(int);
       ++li, ++ui, ++ni)
   {
      std::cout << ls[li] << us[ui] << ns[ni] << "\n";
   }
}

SOURCE

Content is available under GNU Free Documentation License 1.2.