2010-05-18 66 views
0

可能重复:
Howto create combinations of several vectors without hardcoding loops in C++?枚举在C的所有组合++

我的问题是类似于this combinations question但在我的情况我有N(N> 4)小套(1-2现在每组的物品可能会变成3或许4),并且想要生成每组中一个物品的每个组合。

目前的解决方案看起来somethinging沿着这

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); 

简单,有效,合理地可能有效,但丑,不是很可扩展的线。有谁知道更好/更清洁的方式来做到这一点,速度一样快吗?

一个理想的解决方案看起来像一个单一的循环,来自一个良好的支持库。

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]); 
+0

我喜欢Sumudu Fernando对该问题的解决方案 – BCS 2010-05-18 15:30:36

回答

1

如果您需要原始性能(=>没有递归)和组合的长度仅在运行时是已知的,有this code of mine,你能适应。

否则,有更多优雅的解决方案,像KennyTM在他的评论中链接的解决方案。