【问题标题】:print vector of objects within an object打印对象内对象的向量
【发布时间】:2015-10-19 11:15:51
【问题描述】:

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

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

这是我的代码:

#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&lt;Purchase&gt; 传递给ostream&amp; os 之前将其存储起来。但这是不行的。什么是解决这个问题的好方法?

我是 C++ 的新手,刚刚学习流的不同用途,所以如果这是一个愚蠢的问题,请多多包涵。

【问题讨论】:

  • 你拼错了“地址”。

标签: c++ vector ostream ostringstream


【解决方案1】:

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

首先,删除指示部分:

   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

【讨论】:

    【解决方案2】:

    最简单的方法是编写operator&lt;&lt; 的重载,它接受一个对std::vector&lt;Purchase&gt; 的常量引用,然后将向量流式传输到ostream

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

    【讨论】:

    • 这就是他正在做的事情。建议对顶层设计进行细微的更改并不能解释所示代码的问题。
    • 20 行程序中的“顶层设计更改”。好笑。你对 LRiO 感到无聊吗?
    • 放下你的人身攻击一分钟(哇,他们今天似乎很流行 - 满月?)并向我解释你的答案,除了建议将ostream&amp; print(Iter it1, Iter it2, ostream&amp; os, string s)更改为@987654326 @,有什么帮助吗?
    • 在我看来,OP 不知道他可以为向量重载operator&lt;&lt;。意识到他可以这样做将使他能够编写清晰、简洁的代码,因为他已经知道如何为用户定义的对象编写operator&lt;&lt;
    • 谢谢你们!不用打架,你的两个答案对我都有用。 LRiO 回答了我的具体问题,但 RH 设计建议确实让我的程序更清晰、更直接,而且还解决了叠加问题,即打印出我的 Order 向量。
    猜你喜欢
    • 2015-04-24
    • 1970-01-01
    • 2019-03-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多