When I try to find all subsets of a set using the following code, the iterator vit in the inner for loop of the getPowerSet function misses out on one element certain times. Can anyone tell me why?
#include<iostream>
#include<vector>
#include<set>
using namespace std;
vector< set<char> > getPowerSet(const set<char> &given);
void printPowerSet(const vector< set<char> > &powerset);
void printSet(const set<char> &input);
int main()
{
int mychars[] = {'a','b','c','d'};
set<char> given(mychars, mychars+4);
vector< set<char> > powerset = getPowerSet(given);
printPowerSet(powerset);
}
void printSet(const set<char> &input)
{
set<char>::const_iterator it = input.begin();
for( ; it!= input.end(); ++it)
cout << *it << " ";
}
void printPowerSet(const vector< set<char> > &powerset)
{
vector< set<char> >::const_iterator it = powerset.begin();
for( ; it!= powerset.end(); ++it)
{
set<char>::iterator temp = (*it).begin();
for(; temp!=(*it).end(); ++temp)
{
cout<< *temp << " ";
}
cout << endl;
}
}
vector< set<char> > getPowerSet(const set<char> &given)
{
vector< set<char> > powerset;
set<char>::iterator it = given.begin();
for(; it!=given.end(); ++it)
{
set<char> temp;
temp.insert(*it);
powerset.push_back(temp);
vector< set<char> >::iterator vit = powerset.begin();
vector< set<char> >::iterator evit = powerset.end();
for( ; vit!=evit; ++vit)
{
set<char> temp2 = *vit;
temp2.insert(*it);
if(temp2.size() != (*vit).size())
{
powerset.push_back(temp2);
}
}
}
return powerset;
}
I have got the code to work without using iterators in that same loop. Used a variable instead. It works. The logic is the same and if possible I would like someone to tell me what went wrong in the first case.
#include<iostream>
#include<vector>
#include<set>
using namespace std;
vector< set<char> > getPowerSet(const set<char> &given);
int main()
{
int mychars[] = {'a','b','c','d'};
set<char> given(mychars, mychars+4);
/*
{
for(set<char>::iterator it=given.begin(); it!=given.end(); ++it)
cout<< *it << " ";
}
*/
vector< set<char> > powerset = getPowerSet(given);
vector< set<char> >::iterator it = powerset.begin();
for( ; it!= powerset.end(); ++it)
{
set<char>::iterator temp = (*it).begin();
for(; temp!=(*it).end(); ++temp)
{
cout<< *temp << " ";
}
cout << endl;
}
}
vector< set<char> > getPowerSet(const set<char> &given)
{
vector< set<char> > powerset;
set<char>::iterator it = given.begin();
for(; it!=given.end(); ++it)
{
set<char> temp;
temp.insert(*it);
powerset.push_back(temp);
int s = powerset.size();
//vector< set<char> >::iterator vit = powerset.begin();
//vector< set<char> >::iterator evit = powerset.end();
for(int i=0; i< s; ++i)// vit!=evit; ++vit)
{
set<char> temp2 = powerset[i];
int orig = temp2.size();
temp2.insert(*it);
if(temp2.size() != orig)
{
powerset.push_back(temp2);
}
}
}
return powerset;
}