-1

I have a trouble with printing data from priority queue. This data is structure. How can I print structures from my queue?

Here is my structure:

struct pinfo
{
    int p_id;
    char path[50];
    int type;
    int priority;
};

Here I tried to print my data:

void showpq(priority_queue <pinfo> pQueue)
{
    priority_queue <pinfo> g = pQueue;
    while (!g.empty())
    {
        cout << "\t" << g.top();
        g.pop();
    }
    cout << '\n';
}

When I tried to print data I get the error message:

main.cpp:23: error: no match for ‘operator<<’ (operand types are ‘std::basic_ostream<char>’ and ‘const value_type {aka const pinfo}’)
     cout << "\t" << g.top();
Killzone Kid
  • 6,171
  • 3
  • 17
  • 37

2 Answers2

1

This has nothing to do with the data being stored in a priority_queue. You haven't told the program how to print your pinfo type. You need to create an operator<< for it, something like this:

std::ostream& operator<< (std::ostream& os, pinfo const& p)
{
    os << p.p_id << ", " << p.path << ", " << p.type << ", " << p.priority;
    // or however you want the members to be formatted
    return os; // make sure you return the stream so you can chain output operations
}
BoBTFish
  • 19,167
  • 3
  • 49
  • 76
  • This seems like a different problem - I'd guess you don't know how to structure your code in to **components** (`.h` and `.cpp` files). I'd suggest you work through a [good book](https://stackoverflow.com/q/388242/1171191). – BoBTFish May 12 '18 at 18:09
  • That is right solution, but not full, thanks for help! – Viacheslav Shagin May 13 '18 at 09:03
0

You need to define a function with the following signature:

std::ostream& operator<<(std::ostream&&, const pinfo&);

which is known to the compiler when you're piping g.top() to std::cout. The infix << operator simply invokes this function (or an operator<< method of the left-hand-side object). Only a few simple, standard types have an operator<< predefined in the standard library - and the rest need custom definitions.

einpoklum
  • 118,144
  • 57
  • 340
  • 684