打印对象内对象的向量
我试图打印对象Order
(实际上是Order
s的向量)。 Order
有一些数据成员,包括一个带有其他对象的矢量,Purchase
。打印对象内对象的向量
我可以自己打印vector<Purchase>
至cout
,如果我忽略vector<Purchase>
成员,我可以打印vector<Objects>
。但棘手的部分是打印vector<Objects>
与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>
之前,我把它传递给ostream& os
。但这是不行的。什么是解决这个问题的好方法?
我对C++相当陌生,只是在学习流的不同用法,所以如果这是一个愚蠢的问题,请耐心等待。
看起来你有两个小的错别字。
首先,删除指示部分:
oss << print(vpo.begin(), vpo.end(), oss, ", ")
// ↑↑↑↑↑↑↑
然后,在后面的是相同的功能,则不能流a stringstream
,但是可以料流作为其底层缓存器中的字符串,所以使用std::stringstream::str()
:
os << o.name << "\n" << o.adress << "\n" << o.data << "\n"
<< oss.str() << "\n";
// ↑↑↑↑↑↑
随着那些修复到位,并且丢失了read_order
函数,your program compiles。
的确,谢谢! – JEB
最简单的方法是写的operator<<
过载,需要一个const引用到std::vector<Purchase>
,然后就流矢量到ostream
:
std::ostream& operator<<(std::ostream& os, const std::vector<Purchase>& v);
这几乎是他在做什么。提出一个小的顶层设计更改并不能解释所显示的代码有什么问题。在20线方案中,“顶级设计更改”为 –
。 Hilarous。你无聊LRiO? –
放下你的人身攻击一分钟(哇,他们今天似乎很流行 - 满月?),并向我解释你的答案,除了建议改变'ostream&print(Iter it1,Iter it2,ostream&os,字符串s)'转换为'std :: ostream&operator &v)',有帮助吗? –
您拼错“地址”。 –