Maxime Franchot
Maxime Franchot

Reputation: 1103

Iterating through multiple sequential lists in c++

I'm trying to simply iterate through a list, made up of two list objects I have. I want to do this without having to create a third list variable object that is the concatenation of the two, and without two separate loops going each through a list respectively.

I'm pretty sure I've done this before, but I can't find how to do it anymore.

This is the code that I am trying but it doesn't work properly, as it takes what I've written as a list of lists. That is not my intention. I'm looking for it to iterate through elements of list1, then elements of list2. I'm convinced there is a way to format the {list1, list2} within the statement so that this is the case.

for (auto e : {list1, list2}) { // How can I formulate <<<list1, list2>>> 
                                      //  so that it takes the concatenation of list elements?
    std::cout << e << newLine;
}

Looking to have an output like: list1[0], list1[1], list2[0], list2[1].

A simple way to test effectiveness is whether auto registers as the "list type" or the "element type". I'm looking for the element type.

Upvotes: 0

Views: 1051

Answers (1)

Igor Tandetnik
Igor Tandetnik

Reputation: 52471

Something along these lines perhaps:

for (auto& l : {list1, list2}) {
  for (auto& e : l) {
    std::cout << e;
  }
}

Upvotes: 3

Related Questions