1

I know that if I use a c++ container that implements the iterator interface (provides begin() and end() functions) I can use a for loop like this to iterate over it:

for (auto element : container) {
    process(element);
}

If I have two instances of the same type of container, I can write code like this

for (auto element : container1) {
    process(element);
}
for (auto element : container2) {
    process(element);
}

However this leads to repetitive code. I'm looking for a way to combine the two containers so that I can iterate over them at once (i.e. have the for loop iterate over the first one and then continue iterating over the second one). Something like this:

for (auto element : container1 + container2) {
    process(element);
}

I know that I can use stuff like container1.insert(container1.end(), container2.begin(), container2.end()); to concatenate them if they happen to be vectors, but I want to be able to do this more generally, in place, with a single line, and without modifying either container.

Raghav Malik
  • 751
  • 1
  • 6
  • 20
  • There nothing like that in the core C++ language. – Sam Varshavchik Nov 08 '19 at 02:46
  • 1
    Boost has several utilities that come in handy https://stackoverflow.com/questions/14366576/boostrangejoin-for-multiple-ranges – nodakai Nov 08 '19 at 02:51
  • 1
    No. The point of the range-based for is that it iterates over a specified range. Whats wrong with nesting loops (for example, if the containers are all to be unchanged, `for (const auto &container: set_of_containers) for (const auto &element : container) process(element);`)? (Obviously `{}` can be used if things are more complicated, or for readability). – Peter Nov 08 '19 at 02:58

1 Answers1

3

Without using an iterator adapter of some kind, you could just create an array of pointers/references to all of the containers, then loop over that, running an inner loop to iterate the elements of the current container:

auto* containers[] = {&container1, &container2};
for (auto *container : containers) {
    for (auto &element : *container) {
        process(element);
    }
}
Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770