C ++如何打印复合向量的内容

时间:2015-10-23 16:23:33

标签: c++ vector stl

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

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

它完美无缺。但是如果我的矢量是vector<pair<int, struct node>>类型怎么办?如何使用上述方法打印此矢量?

我试过

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&amp; std :: operator&lt;&lt;(std :: basic_ostream&amp;,const unsigned char *)
       operator&lt;&lt;(basic_ostream&amp; __out,const unsigned char * __s)        ^
  /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&lt;&lt; __value;

无法弄清楚。有什么帮助吗?

2 个答案:

答案 0 :(得分:2)

#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, " "));

}

您必须超载<<才能打印pair<int, struct node>并重载<<以打印node

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

答案 1 :(得分:1)

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

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