0

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

我可以自己打印vector<Purchase>到,如果我忽略该成员cout,我可以打印。但棘手的部分是包含在内的打印。vector<Objects>vector<Purchase>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++ 还很陌生,只是在学习流的不同用途,所以如果这是一个愚蠢的问题,请多多包涵。

4

2 回答 2

2

看起来你有两个小错别字。

首先,删除指示的部分:

   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抽象掉了缺失的函数,你的程序就可以编译.

于 2015-10-19T11:23:20.323 回答
-2

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

std::ostream& operator<<(std::ostream& os, const std::vector<Purchase>& v);
于 2015-10-19T11:23:14.453 回答