枚举 c++ 中的所有组合

发布于 2024-09-02 04:03:47 字数 1201 浏览 1 评论 0原文

可能的重复:
如何在不使用硬编码循环的情况下创建多个向量的组合C++?

我的问题类似于这个组合问题 但就我而言,我有 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]);

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 library.

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

旧城烟雨 2024-09-09 04:03:47

如果您需要原始性能(=>无递归)并且组合的长度仅在运行时已知,则可以使用 我的这段代码,您可以修改。

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

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文