【问题标题】:enumerate all combinations in c++ [duplicate]枚举C++中的所有组合[重复]
【发布时间】:2010-05-18 14:59:40
【问题描述】:

可能重复:
Howto create combinations of several vectors without hardcoding loops in C++?

我的问题类似于this combinations question,但在我的情况下,我有 N (N > 4) 个小集合(现在每组 1-2 个项目可能会增加到 3 个或 4 个)并且想要生成一个项目的每个组合每组。

当前的解决方案看起来与此类似

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

【问题讨论】:

  • 我喜欢 Sumudu Fernando 对该问题的解决方案

标签: c++ iterator combinations


【解决方案1】:

如果您需要原始性能(=>无递归)并且组合的长度仅在运行时知道,您可以调整 this code of mine

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-26
    • 1970-01-01
    相关资源
    最近更新 更多