0

虽然有很多关于如何生成集合的实际幂集的示例,但我找不到任何关于迭代(如std::iterator)生成幂集的信息。我会欣赏这种算法的原因是我的基集的大小。由于 n 元素集的幂集有 2^n 个元素,因此在实际计算该集时我会很快耗尽内存。那么,有没有办法为给定集合的幂集创建迭代器?甚至可能吗?

  • 如果它更容易,创建ints 集合的迭代器会很好 - 我可以将它们用作实际集合/向量的索引。
  • 当我实际工作时std::vector,如果需要,随机访问是可能的
4

1 回答 1

3

使用for_each_combinationfrom Combinations 和 Permutations可以轻松地遍历 a 的幂集的所有成员std::vector<AnyType>。例如:

#include <vector>
#include <iostream>
#include "../combinations/combinations"

int
main()
{
    std::vector<int> v{1, 2, 3, 4, 5};
    std::size_t num_visits = 0;
    for (std::size_t k = 0; k <= v.size(); ++k)
        for_each_combination(v.begin(), v.begin()+k, v.end(),
            [&](auto first, auto last)
            {
                std::cout << '{';
                if (first != last)
                {
                    std::cout << *first;
                    for (++first; first != last; ++first)
                        std::cout << ", " << *first;
                }
                std::cout << "}\n";
                ++num_visits;
                return false;
            });
    std::cout << "num_visits = " << num_visits << '\n';
}

this 访问 this 的每个幂集成员vector,并执行函子,它简单地计算访问次数并打印出当前的幂集:

{}
{1}
{2}
{3}
{4}
{5}
{1, 2}
{1, 3}
{1, 4}
{1, 5}
{2, 3}
{2, 4}
{2, 5}
{3, 4}
{3, 5}
{4, 5}
{1, 2, 3}
{1, 2, 4}
{1, 2, 5}
{1, 3, 4}
{1, 3, 5}
{1, 4, 5}
{2, 3, 4}
{2, 3, 5}
{2, 4, 5}
{3, 4, 5}
{1, 2, 3, 4}
{1, 2, 3, 5}
{1, 2, 4, 5}
{1, 3, 4, 5}
{2, 3, 4, 5}
{1, 2, 3, 4, 5}
num_visits = 32

我上面使用的语法是 C++14。如果您有 C++11,则需要更改:

[&](auto first, auto last)

至:

[&](std::vector<int>::const_iterator first, std::vector<int>::const_iterator last)

如果你在 C++98/03 中,你将不得不编写一个仿函数或函数来替换 lambda。

for_each_combination函数不分配额外的存储空间。这都是通过将成员交换vector到范围来完成的[v.begin(), v.begin()+k)。在每次调用for_each_combination向量结束时,都会保持其原始状态。

如果由于某种原因您想提前“退出” for_each_combination,只需返回true而不是false.

于 2014-09-22T23:49:10.617 回答