Search code examples
c++iteratorsetnested-sets

how to iterate through a set of sets C++


Pretty new to C++, only at it a week or so, I want to iterate through a set of nested sets and write each element in the inner set to a line in a file. Each inner set has 3 elements and I want all three elements on the same line. I have a set up as follows:

   // Define "bigSet" and initiate as empty set "Triplets"
   typedef set < set<string> > bigSet;
   bigSet Triplets;

I tried something of this sort to go through it but it gives me an error...

    // Iterate through and print output
    set <string>::iterator it;
    for(it = Triplets.begin(); it != Triplets.end(); it++){
        cout << *it << endl;
    }

Any help is greatly appreciated guys thank you!


Solution

  • I would do it this way:

     // Iterate through and print output
        set < set <string> >::iterator it_ex; // iterator for the "outer" structure
        set <string>::iterator it_in; // iterator for the "inner" structure
    
        for(it_ex = Triplets.begin(); it_ex != Triplets.end(); it_ex++)
        {
            for(it_in = it_ex->begin(); it_in != it_ex->end(); it_in++)   
                cout << *it_in << ", ";
            cout << endl;
        }