通过运算符重载写入地图的内容

时间:2014-12-30 23:14:35

标签: c++ dictionary containers overloading ostream

我试图使用运算符重载来打印不同类型的容器。但是,当我想打印map<int, stack<vector<int > > >时,它返回一个空字符串,其中应该是堆栈。 当我尝试单独打印堆栈时,我没有任何问题。

#include <vector>
#include <stack>
#include <deque>
#include <set>
#include <iostream>
#include <map>
using namespace std;

typedef struct {
   string naam;
   int leeftijd;
}Persoon;

ostream& operator<<(ostream& out, const Persoon &p) {
   out<<"! "<<p.naam<<" "<<p.leeftijd<<" !";
   return out;
}
template<typename D, typename T>
ostream& operator<<(ostream&out, map<T,D> &m) {
   typename map<T,D>::iterator my_it = m.begin();
   out<<"[*] ";
   while(my_it != m.end()) {
      cout<<my_it->first<< " -> "<<my_it->second<<" ";
      my_it++;
   }
   out<<"[*]\n";
}
template<typename T>
ostream& operator<<(ostream& out, vector<T> &v){
   out<<"[";
   int i;
   for(i = 0; i < v.size()-1; i++) {
      out<<v[i]<<"|";   
   }
   out<<v[i]<<"]\n";
   return out;
}
template <typename T>
ostream& operator<<(ostream& out, stack<T> &s){
   out<<"{";
   while(!s.empty()) {
      out<<"|"<<s.top()<<"|";
      s.pop();  
   }
   out<<"}\n";
   return out;
}
int main() {
   vector<int> v(5,3);
   /*cout<<v;
     stack<string> s;
     s.push("Plate1");
     s.push("Plate2");
     s.push("Plate3");
     cout<<s;
     map<int, Persoon> m;
     Persoon Bill = {"Bill",59};
     Persoon Steven = {"Steven",79};
     Persoon Rob = {"Rob",26};

     m.insert(pair<int,Persoon>(59,Bill));
     m.insert(pair<int,Persoon>(79,Steven));
     m.insert(pair<int,Persoon>(26,Rob));
     cout<<m;
    */
   stack<vector<int> > s2;
   s2.push(v);
   s2.push(v);
   cout<<s2;

   map<int, stack<vector<int> > > m2;
   m2.insert(pair<int, stack<vector<int> > >(5,s2));
   cout<<m2;
}

1 个答案:

答案 0 :(得分:2)

您的运营商&lt;&lt;对于堆栈,会弹出堆栈中的所有元素,因此当您复制堆栈以放入映射时,堆栈为空。

要演示,如果我将main()更改为:

    int main() {
        stack<int> s2;
        s2.push(1);
        s2.push(2);
        cout << s2.size() << '\n';
        cout << s2;
        cout << s2.size() << '\n';
    }

输出结果为:

2
{|2||1|}
0

据我所知,popping是在堆栈元素上“迭代”的唯一方法(即使在C ++ 11中),所以你可能别无选择,只能在运算符中复制堆栈。弹出所有副本的元素。这段代码似乎对我有用:

    ostream& operator<<(ostream& out, stack<T> &s){
        stack<T> scopy = s;
        out<<"{";
        while(!scopy.empty()) {
            out<<"|"<<scopy.top()<<"|";
            scopy.pop();    
        }
        out<<"}\n";
        return out;
    }