0

I am trying to make a priority queue which top most element contains the smallest integer. I made a function object for comparison. Everything is going well but, whenever I try to print out the top most element std::cout<<pq.top<<std::endl I get an error that says:

candidate function not viable: no known conversion from 'const value_type' (aka 'const Foo') to 'const void *' for 1st argument; take the address of the argument with & basic_ostream& operator<<(const void* __p); 

I am really new to programming so, I really don't know what to do.

#include<iostream> #include<queue> #include <vector> class Foo { public: int data; Foo(int data): data(data) {} }; class Compare { public: int operator() (Foo dat1, Foo dat2) { if( dat1.data < dat2.data ) return dat1.data; else return dat2.data; } }; int main() { std::priority_queue<Foo, std::vector<Foo>, Compare> pq; pq.push(5); pq.push(7); pq.push(1); pq.push(2); pq.push(3); std::cout << pq.top() << std::endl; return 0; } 
1
  • You seem to have missed the end of your sentence "but whenaver I try..:" what happens then? What is the problem? Commented Jan 19, 2016 at 13:34

2 Answers 2

2

You never defined a way to output a Foo. You can use

std::cout << pq.top().data << std::endl; 

Or you can overload the operator<< for Foo to output it like

class Foo { public: int data; Foo(int data) : data(data) {} friend std::ostream & operator<<(std::ostream& os, const Foo & f) { return os << f.data; } }; 

You also have an issue with your comparision function. The comparison function should return true if dat1.data > dat2.data in order to get the smallest element to the top. With that you should change it to:

bool operator() (const Foo& dat1, const Foo& dat2) { return dat1.data > dat2.data; } 
Sign up to request clarification or add additional context in comments.

1 Comment

Also, I would prefer to have the bool operator() taking const references to Foo (const Foo &).
0
std::cout << pq.top() << std::endl; 

The call pq.top() in the above line returns a Foo object, which your program does not know to print. So that generates the error. By using &pq.top() you can print the address of the object, but since this is not the case you want to do right now, you can use pq.top().data to access the data item and print it.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.