Power Set
Sep 25, 2011 at 5:08pm UTC
Hi,
I need to calculate the power set of a set of a given numbers (not for a homework assignment). I found a piece of code online:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78
#include <iostream>
#include <set>
#include <vector>
#include <iterator>
#include <algorithm>
typedef std::set<int > set_type;
typedef std::set<set_type> powerset_type;
powerset_type powerset(set_type const & set)
{
typedef set_type::const_iterator set_iter;
typedef std::vector<set_iter> vec;
typedef vec::iterator vec_iter;
struct local
{
static int dereference(set_iter v) { return *v; }
};
powerset_type result;
vec elements;
do
{
set_type tmp;
transform(elements.begin(), elements.end(),
std::inserter(tmp, tmp.end()),
local::dereference);
result.insert(tmp);
if (!elements.empty() && ++elements.back() == set.end())
{
elements.pop_back();
}
else
{
set_iter iter;
if (elements.empty())
{
iter = set.begin();
}
else
{
iter = elements.back();
++iter;
}
for (; iter != set.end(); ++iter)
{
elements.push_back(iter);
}
}
} while (!elements.empty());
return result;
}
int main()
{
int values[4] = { 2, 3, 5, 7 };
set_type test_set(values, values+4);
powerset_type test_powerset = powerset(test_set);
for (powerset_type::iterator iter = test_powerset.begin();
iter != test_powerset.end();
++iter)
{
std::cout << "{ " ;
char const * prefix = "" ;
for (set_type::iterator iter2 = iter->begin();
iter2 != iter->end();
++iter2)
{
std::cout << prefix << *iter2;
prefix = ", " ;
}
std::cout << " }\n" ;
}
}
However, when I try to compile this, it tells me:
In function `powerset(std::set<int, std::less<int>, std::allocator<int> > const&)':
/usr/include/c++/4.5/bits/stl_tree.h:1224: multiple definition of `powerset(std::set<int, std::less<int>, std::allocator<int> > const&)'
Sep 25, 2011 at 7:12pm UTC
Hi duude1234,
compiles fine on my mac (gcc 4.2.1)
./power
{ }
{ 2 }
{ 2, 3 }
{ 2, 3, 5 }
{ 2, 3, 5, 7 }
{ 2, 3, 7 }
{ 2, 5 }
{ 2, 5, 7 }
{ 2, 7 }
{ 3 }
{ 3, 5 }
{ 3, 5, 7 }
{ 3, 7 }
{ 5 }
{ 5, 7 }
{ 7 }
Sep 25, 2011 at 7:46pm UTC
Also complies fine for me using g++ 4.5.2 on Ubuntu Linux
Topic archived. No new replies allowed.