Amor Diaz
Amor Diaz

Reputation: 41

How to print what is in a Set of Sets with an iterator?

I'm trying to print out the contents of my powerSet which is a set of a given set, however when I try to iterate through my powerSet, I get a C2679 Error of << binary "<<" with this following function.

template <typename T>
void writePowerSet(const set<set<T>>& pSet) 
{
    for(typename set< set<T> >::const_iterator itr = pSet.begin(); itr != pSet.end(); itr++)
    {
        cout << *itr;
    }
}

I know that in order to print a set, you must iterate through it and deference the iterator, however that is what is yielding my error. Is there a different way to approach it?

Upvotes: 0

Views: 85

Answers (1)

user10605163
user10605163

Reputation:

pSet is a reference of type std::set<std::set<T>>, so *itr will be a reference of type std::set<T>. You are trying to use the std::ostream overload of << on this type. However the standard library container do not define such an overload.

If you want to print all elements of the inner set, you need to iterate over it as well:

template <typename T>
void writePowerSet(const std::set<std::set<T>>& pSet) 
{
    for(const auto& s : pSet)
    {
        for(const auto& x : s)
        {
            std::cout << x;
        }
     }
}

Here I am using the range-based for loop, because it is easier to write and read. The output will not look nice, add additional output where you'd like it.

This is also assuming that the << overload is defined for the inner type T.

Upvotes: 2

Related Questions