powerset

G

Gunnar G

I have a
vector<int> x;
and I would like to
call the function

foo( a_subset_of_x )

for ALL subsets of x (i.e. the powerset of x)

Is this possible in an easy way?
 
K

Karl Heinz Buchegger

Gunnar said:
I have a
vector<int> x;
and I would like to
call the function

foo( a_subset_of_x )

for ALL subsets of x (i.e. the powerset of x)

Is this possible in an easy way?

Use a recursive function

#include <iostream>
#include <vector>

using namespace std;

typedef vector<int> Set;

void PrintSet( int Count, Set& TheSet )
{
cout << Count << ": ";
for( size_t i = 0; i < TheSet.size(); ++i )
cout << TheSet << " ";
cout << endl;
}

void Iterate( int& Count, int StartWith, Set& TheSet, Set& Helper )
{
PrintSet( Count, Helper );
Count++;

for( size_t i = StartWith; i < TheSet.size(); ++i ) {
Helper.push_back( TheSet );
Iterate( Count, i + 1, TheSet, Helper );
Helper.pop_back();
}
}

void Iterate( Set& TheSet )
{
Set Tmp;
int Cnt = 1;
Iterate( Cnt, 0, TheSet, Tmp );
}

int main()
{
Set S;

S.push_back( 1 );
S.push_back( 2 );
S.push_back( 3 );
S.push_back( 5 );
S.push_back( 7 );
S.push_back( 11 );

Iterate( S );

return 0;
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,055
Latest member
SlimSparkKetoACVReview

Latest Threads

Top