mercredi 23 janvier 2019

Is there a way to iterate over two containers without using two for loops

Is there a way to iterate over two containers (one followed by the other), without using two for loops.

My intention is to do something like this

vector<int> a{ 1,2,3 };
vector<int> b{ 4,5,6 };

auto it = a.begin();
auto end = b.end();

for (; it != end; ++it)
{
    if (it == a.end())
    {
        it == b.begin();
    }
    // do something with *it
}

to print

1 2 3 4 5 6

(of course it doesn't work)

I do not want to write two for loops and duplicate the code inside the loop. Is there a way to iterate over a followed by b with a single for loop?

The only thing I can think of is either copy/move the second container to the first or create a new vector combining a and b, and then iterate over it. I do not want to do this either, because this will mean expensive copy operations.

Aucun commentaire:

Enregistrer un commentaire