views:

250

answers:

1

Hi, similar questions have been asked before but I cant find an exact match to my question.

I have 4 vectors each of which hold between 200-500 4 digit integers. The exact number of elements in each vector varies but I could fix it to a specific value. I need to find all possible combinations of the elements in these 4 vectors.

eg:

v1[10, 30] v2[11, 45] v3[63, 56] v4[82, 98]

so I'd get something like this:

[10, 11, 63, 82]; [30, 11, 63, 82]; [10, 45, 63, 82]; [10, 45, 56, 82] etc..

Is there a common name for this algorithm so I can find some references to it online? Otherwise any tips on implementing this in C++ would be helpful. Performance isn't much of an issue as I only need to run the algorithm once. Is there anything built into the STL?

+7  A: 

Not much of an algorithm...

for(vector<int>::const_iterator i1 = v1.begin(); i1 != v1.end(); ++i1)
    for(vector<int>::const_iterator i2 = v2.begin(); i2 != v2.end(); ++i2)
        for(vector<int>::const_iterator i3 = v3.begin(); i3 != v3.end(); ++i3)
            for(vector<int>::const_iterator i4 = v4.begin(); i4 != v4.end(); ++i4)
                cout << "[" << *i1 << "," << *i2 << "," << *i3 << "," << *i4 << "]" << endl;
Andrew Stein
+1 This is the logical way to do it. There might be a prettier way to represent but the process would be the same.
Kirk Broadhurst
It's times like these you wish you had a meta-for loop that could loop through the for loops.
Peter Alexander
+1 Thanks, this is working of course. I agree with Poita about the meta loop comment.
Stephen Blinkhorn