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