2

I read this post How to print out the contents of a vector?, one beautiful answer to it is to print contents of a vector the following way

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

It works perfectly fine. But what if my vector is of type vector<pair<int, struct node>>. How do I use the above method to print this vector?

I tried

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

I am getting huge error dump, few lines are as follows

In file included from /usr/include/c++/4.9/iterator:64:0,
from dijkstra.cpp:8:
/usr/include/c++/4.9/ostream:548:5: note: template std::basic_ostream& std::operator<<(std::basic_ostream&, const unsigned char*)
operator<<(basic_ostream& __out, const unsigned char* __s) ^
/usr/include/c++/4.9/ostream:548:5: note: template argument deduction/substitution failed:
In file included from /usr/include/c++/4.9/iterator:66:0, from dijkstra.cpp:8:
/usr/include/c++/4.9/bits/stream_iterator.h:198:13: note: cannot convert ‘__value’ (type ‘const std::pair’) to type ‘const unsigned char*’ *_M_stream << __value;

Not able to figure out. Any help?

Community
  • 1
  • 1
mtk
  • 13,221
  • 16
  • 72
  • 112

2 Answers2

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

}

You have to overload << for printing out pair<int, struct node> and also overload << for printing out node.

I have given an example above. You have to change the implementation of node and also the overloaded << for node as per your requirement.

user93353
  • 13,733
  • 8
  • 60
  • 122
1

There is no default output for a pair, so you need to declare your operator<< for that:

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;
}

See live demo.

jpo38
  • 20,821
  • 10
  • 70
  • 151