【问题标题】:How to print a vector如何打印矢量
【发布时间】:2015-10-21 13:13:18
【问题描述】:

我必须打印一对的值。对于显示该对的第一个值的值没有任何问题。但是我如何打印该对的第二个值? 表示无法更改。

typedef vector<char> _vots;
typedef pair<string,_vots> PartitPolitic;

ostream& operator<<(ostream &o, PartitPolitic x){
   o << x.first << endl;
   o << x.second << endl;->>>>>>>>>>>>>>>>> ERROR
   return o;
}

int main(){
      vector<PartitPolitic> partit;
      string q;
      string s;
      getline(cin,descripcio);
      while (q!="*"){
          getline(cin,s)
          _vots v(s.begin(),s.end());
          PartitPolitic f(descripcio,v);
          partit.push_back(f);
          getline(cin,descripcio);
     }
     vector<PartitPolitic>::iterator it =partit.begin();
     while(it!=partit.end()){
        cout << *it << endl;
        it++;
     }
     return 0;
}

【问题讨论】:

标签: c++ vector stl stdvector cout


【解决方案1】:

如何打印该对的第二个值?

第二个值是vector&lt;char&gt;,因此要打印,您需要为vector 提供operator&lt;&lt; 重载,定义您希望如何打印矢量:

template<typename elem_type>
ostream& operator<<(ostream &o, vector<elem_type> const& v) {
   for (const elem_type& e : v)
      o << e << ",";
   return o;
}

或者你可以简单地在operator&lt;&lt;(ostream&amp;, PartitPolitic)中手动输出向量:

ostream& operator<<(ostream &o, PartitPolitic x) {
   o << x.first << endl;
   for (char e : x.second)
      o << e << ",";
   return o;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-09-08
    • 1970-01-01
    • 1970-01-01
    • 2017-08-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多