C++: Loop Over Multiple Arrays Simultaneously


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


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


Content is available under GNU Free Documentation License 1.2.

Our team found a curious site for our readers that are fans of online gaming, a rather exciting site that provides the latest gaming technology. Casinodots.com is the site, they compile the best reviews of MGA casino utan svensk licens sites. This site might pique your curiosity and you can win extra money!