Iterating over a set

24 views Asked by At

I'm trying to write some code that overrides the << operator for a given set, so it actually gives me the set between "{...}".

template<typename T>
ostream& operator<<(ostream& out, const set<T> & v){    
    iterator myIt = v.begin();
    out << "{";
    while(myIt != v.end()-1) {
     out<<*myIt<<",";
     myIt++;
}
out << *myIt << "}";
return out;
}

However this does not seem to work, someone who is willing to give me some advice?

1

There are 1 answers

0
Michel Billaud On

It doesn't even compile correctly. Another problem is, you suppose your set is not empty.

C++11's facilities help a lot:

  • range-based for loop
  • type deduction

`

template <typename T>
 ostream & operator<<(ostream& out, const set<T> & v) {
  string sep = "{";
  for (const auto &it : v) {
    out << sep << it << v;
    sep = ",";
  }
  return out << "}";
 }