【问题标题】:Generating all possible combination of the elements of integer vector in c++在c ++中生成整数向量元素的所有可能组合
【发布时间】:2013-02-14 18:31:11
【问题描述】:

我有一个大小为“n”的整数向量。

e.g.
std::vector<int> vec;
vec.pushback(0);
vec.pushback(1);
vec.pushback(2);
vec.pushback(3);
....

现在我想生成 size = {0, 1, 2, ... , n} 的所有可能组合。

请记住 {0, 1, 3} 不等于 {3, 1, 0} 或 {1, 0, 3} 或 {3, 0, 1}

如果你有想法,请帮助我。

提前致谢。

【问题讨论】:

  • @Mat 感谢您的回复,nexr_permutation 会生成固定大小的组合,但是我如何重复应用它以适应不同的大小。
  • 查看右侧“相关”部分中的链接。所有这些都已经被问到并得到了回答,您需要挑选碎片并使其适合您的场景。
  • @user986789 你似乎不愿意自己做任何研究。解决方案涉及组合和排列。

标签: c++ vector combinations


【解决方案1】:

你可以这样做:

#include<iostream>
#include<algorithm>
#include <vector>

    std::ostream& operator<< (std::ostream& os, std::vector<int> v)
    {
        for (auto it = v.begin(); it != v.end(); ++it)
        {
           os << *it << ",";
        }
        return os;
    }

int main()
{
   std::vector<int> v;
   v.push_back(1);
   v.push_back(2);
   v.push_back(3);
    do {
       std::cout << v;
    } while (std::next_permutation(v.begin(), v.end()));

}

根据@JamesKanze 的评论,这只有在向量开始排序时才有效,所以如果你有一个未排序的向量,你应该先调用std::sort

看着this,它说:

根据operator&lt;comp 按字典顺序将所有排列集合中的范围 [first, last) 转换为下一个排列。

你可以看到它在行动here

【讨论】:

  • 您可能会提到这仅在列表按开头排序时才有效。
  • @Tony 感谢您的回复,我看到它会生成固定大小的组合,但是我如何重复应用它来生成不同大小的组合,即 1、2 和 3
  • 我认为最简单的方法是每次矢量大小发生变化时再次调用该函数。
  • 只需将其调整为您想要的数字即可。
猜你喜欢
  • 2023-03-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-04-16
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多