2010-05-18 65 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在他的評論中鏈接的解決方案。