【问题标题】:C++ How to print contents of composite vectorC++如何打印复合向量的内容
【发布时间】:2016-01-23 06:36:05
【问题描述】:

我读了这篇文章How to print out the contents of a vector?,其中一个beautiful answer 是通过以下方式打印向量的内容

std::copy(path.begin(), path.end(), std::ostream_iterator<char>(std::cout, " "));

它工作得很好。但是如果我的向量是vector&lt;pair&lt;int, struct node&gt;&gt; 类型的呢?如何使用上述方法打印这个向量?

我试过了

std::copy(path.begin(), path.end(), std::ostream_iterator<pair<int, struct node>>(std::cout, " "));

我得到了巨大的错误转储,几行如下

在 /usr/include/c++/4.9/iterator:64:0 中包含的文件中,
来自 dijkstra.cpp:8:
/usr/include/c++/4.9/ostream:548:5: 注意:模板 std::basic_ostream& std::operator 运算符 /usr/include/c++/4.9/ostream:548:5:注意:模板参数推导/替换失败:
在 /usr/include/c++/4.9/iterator:66:0 包含的文件中, 来自 dijkstra.cpp:8:
/usr/include/c++/4.9/bits/stream_iterator.h:198:13:注意:无法将“__value”(类型“const std::pair”)转换为类型“const unsigned char*” *_M_stream

想不通。有什么帮助吗?

【问题讨论】:

标签: c++ vector stl


【解决方案1】:
#include <vector>
#include <iostream>
#include <iterator>
#include <algorithm>
#include <utility>

struct node
{
    private:
    int x;

    friend std::ostream& operator << (std::ostream& o, const node & n);
};


std::ostream& operator << (std::ostream& o, const node & n)
{
    return o << n.x;
}


std::ostream& operator << (std::ostream& o, const std::pair<int, struct node> & p)
{
    return o << p.first<< " "<<p.second;
}



int main()
{
    std::vector<std::pair<int, struct node> > path;

    std::copy(path.begin(), path.end(), std::ostream_iterator<std::pair<int, struct node> >(std::cout, " "));

}

您必须重载&lt;&lt; 才能打印出pair&lt;int, struct node&gt;,还必须重载&lt;&lt; 才能打印出node

我在上面给出了一个例子。您必须根据您的要求更改node 的实现以及节点的重载&lt;&lt;

【讨论】:

    【解决方案2】:

    一对没有默认输出,因此您需要为此声明operator&lt;&lt;

    std::ostream& operator<<( std::ostream& os, const pair<int, struct node>& obj )
    {
        os << obj.first;
        // here, you need to output obj.second, which is a node object
        // Possibly, you can define a operator<< for a struct node and then simply do:
        // os << ";" << obj.second;
        return os;
    }
    

    live demo

    【讨论】:

      猜你喜欢
      • 2021-05-12
      • 1970-01-01
      • 2022-06-15
      • 2011-01-23
      • 2018-05-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-08-09
      相关资源
      最近更新 更多