enumerate all combinations in c++ [duplicate]
Possible Duplicate:
Howto create combinations of several vectors without hardcoding loops in C++?
My question is similar to this combinations question but in my case I have N (N > 4) small sets (1-2 items per set for now might go to 3 maybe 4) and want to generate each combination of one item from each set.
The current solution looks somethinging along the lines of this
for(T:: iterator a = setA.begin(); a != setA.end(); ++a)
for(T:: iterator b = setB.begin(); b != setB.end(); ++b)
for(T:: iterator c = setC.begin(); c != setC.end(); ++c)
for(T:: iterator d = setD.begin(); d != setD.end(); ++d)
for(T:: iterator e = setE.begin(); e != setE.end(); ++e)
something(*a,*b,*c,*d,*e);
Simple, effective, probably reasonably efficient, but ugly and not very extensible. Does anyone know of a better/cleaner way to do this that is just as fast?
An ideal solution would look like a single loop and come from some well supported libr开发者_开发百科ary.
Combinations<T> comb;
comb.set(0) = setA;
comb.set(1) = setB;
comb.set(2) = setC;
comb.set(3) = setD;
comb.set(4) = setE;
for(Combinations<T>::iterator a = comb.begin(); a != comb.end(); ++a)
something(*a[0],*a[1],*a[2],*a[3],*a[4]);
If you need raw performance (=>no recursion) and length of the combination is known only at runtime, there's this code of mine that you can adapt.
Otherwise, there are more elegant solutions like the ones linked by KennyTM in his comment.
精彩评论