打印对象内的对象矢量

时间:2015-10-19 11:15:51

标签: c++ vector ostream ostringstream

我试图打印一个对象Order(实际上是Order s的向量)。 Order有一些数据成员,包括带有其他对象的向量Purchase

我可以自行打印vector<Purchase>cout,如果忽略vector<Objects>成员,我可以打印vector<Purchase>。但棘手的部分是打印包含vector<Objects>的{​​{1}}。

这是我的代码:

vector<Purchase>

正如您所看到的,我有一个想法是使用#include <iostream> #include <string> #include <fstream> #include <vector> #include <algorithm> #include <sstream> using namespace std; struct Purchase { string name; double unit_price; int count; }; struct Order { string name; string adress; double data; vector<Purchase> vp; }; template<typename Iter> //this is my general print-vector function ostream& print(Iter it1, Iter it2, ostream& os, string s) { while (it1 != it2) { os << *it1 << s; ++it1; } return os << "\n"; } ostream& operator<<(ostream& os, Purchase p) { return os << "(" << p.name << ", " << p.unit_price << ", " << p.count << ")"; } ostream& operator<<(ostream& os, Order o) { vector<Purchase> vpo = o.vp; ostringstream oss; oss << print(vpo.begin(), vpo.end(), oss, ", "); //This is what I would like to do, but the compiler doesn't like this conversion (from ostream& to ostringstream) os << o.name << "\n" << o.adress << "\n" << o.data << "\n" << oss << "\n"; return os; } int main() { ifstream infile("infile.txt"); vector<Order> vo; read_order(infile, vo); //a function that reads a txt-file into my vector vo print(vo.begin(), vo.end(), cout, ""); return 0; } 作为临时变量,我会在将ostringstreams传递给vector<Purchase>之前将其存储起来。但这是不行的。什么是这个问题的好方法?

我是C ++的新手,只是在学习不同的流程用途,所以如果这是一个愚蠢的问题,请耐心等待。

2 个答案:

答案 0 :(得分:2)

看起来你有两个小错字。

首先,删除指定的部分:

   oss << print(vpo.begin(), vpo.end(), oss, ", ")
// ↑↑↑↑↑↑↑

然后,稍后在同一个函数中,您无法流式传输stringstream,但您可以将字符串作为其底层缓冲区流式传输,因此请使用std::stringstream::str()

os << o.name << "\n" << o.adress << "\n" << o.data << "\n"
    << oss.str() << "\n";
//        ↑↑↑↑↑↑

有了这些修补程序,并且遗漏了read_order函数,your program compiles

答案 1 :(得分:-2)

最简单的方法是编写operator<<的重载,对std::vector<Purchase>进行const引用,然后将向量流式传输到ostream

std::ostream& operator<<(std::ostream& os, const std::vector<Purchase>& v);
相关问题