Saturday, July 23, 2005

Set of Sets in STL

 // WHAT: print set of set in C++ STL with generate_allsubets example.
 // file setofsets.cpp
 // Testing VC6.

 #include <set>
 #include <iostream>
 #include <algorithm>
 using namespace std;

 #pragma warning(disable:4786) // warning: debug identifier trunc to 255.

 typedef set< set<int> > tsos;
 typedef set<int> ts;

 void generate_allsubets( tsos& sos, ts& choices ){
     if( choices.size() < 1 ) return; // end of recursion.
     if( sos.size() < 1 )
         sos.insert(*new set<int>); // insert emptyset first time.
     int c1 = *(choices.begin());
     // make a copy of sos, in each subset insert c1.
     tsos sos_c1;
     for( tsos::iterator p = sos.begin(); p != sos.end(); ++p ){
         ts s_c1 = *p; // make a copy of the subset, then insert c1.
         s_c1.insert(c1);
         sos_c1.insert(s_c1);
     }
     // we have two sets of subset now: sos_c1 with c1, original sos without c1.
     // merge sos_c1 into sos to double the size of sos.

     #if 0 // USE set_union
     tsos both;
     set_union( sos.begin(), sos.end(), sos_c1.begin(), sos_c1.end(), 
                         insert_iterator<tsos>(both,both.begin()) );
     sos = both;
     #else
     for( tsos::iterator pc1 = sos_c1.begin(); pc1 != sos_c1.end(); ++pc1 )
         sos.insert( *pc1 );
     #endif

     // Recursively insert remaining choices.
     if( choices.erase(c1) > 0 ) // should always be able to erase c1.
         generate_allsubets( sos, choices );
 }

 void print_allsubsets( tsos& sos ){
     int i=0;
     for( tsos::iterator p = sos.begin(); p != sos.end(); ++p ){
         cout << "subset " << ++i << " = { ";
         for( ts::iterator q = p->begin(); q != p->end(); ++q )
              cout << *q << ", ";
         cout << "}\n";
     }
 }

 int main( int argc, char *argv[] ){
     set< set<int> > sos;
     set< int > choices;
     for(int i=0;i<3;i++)
         choices.insert(i);
     generate_allsubets( sos, choices );
     cout << "The "<< sos.size() << " subsets of {0.."<<i-1<<"} are\n";
     print_allsubsets( sos );
     return 0;
 }
 

0 Comments:

Post a Comment

<< Home