简体   繁体   中英

C++ programming candidate function not viable

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM