0

I am trying to print a priority queue however it is giving me the following error:

[Error] passing 'const value_type {aka const Horse}' as 'this' argument of 'void Horse::print()' discards qualifiers [-fpermissive]

here is how my code is laid out:

struct horse {
  std::string horseName;
  int win;
  void print() {
    std::cout<<"name: " << horseName<<std::endl;
  }

  bool operator < (Horse h) const {
    if (h.win < win)
      return true;

    return false;
  }
};

class Horses {
  public:
    std::vector<Horse> horses;
  void printPriorityQ(std::priority_queue<Horse> q) {
    while (!q.empty()) {
      q.top().print();
      q.pop();
    }
    std::cout << std::endl;
  }
  void testing();
};

and this is how i am using it:

void Horses::testing() {

  Horse h;
  h.horseName = "max";
  h.win = 3;
  horses.push_back(h);
  h.horseName = "bob";
  h.win = 3;
  horses.push_back(h);

  std::priority_queue<Horse> winner;
  for (size_t i=0; i<horses.size(); i++)
    results.push(horses[i]);

  printPriorityQ(results);

}

my expected output should be to print the horse name based on the order of the win variable in my horse struct.

EDIT: is my overload operator correct? I seen on the other thread in the comments below they write it as:

bool operator < ( const Horse& h, const Horse& hh) const {
  if (h.win < hh.win)
    return true;

  return false;
}
Rahul Bhobe
  • 4,165
  • 4
  • 17
  • 32
william_
  • 1,131
  • 6
  • 20
  • try declaring the operator outside the class like mentioned in this thread https://stackoverflow.com/questions/19535644/how-to-use-the-priority-queue-stl-for-objects – SR810 Jul 19 '20 at 05:02
  • Next time, please try writing up a minimal example that reproduces your problem. This process often makes you find the problem yourself, but also saves us readers the hassle of having to read through and understand the rest of your code. Also, you should format your code in your questions (or answers) with proper indentations to make it readable. – Elliott Jul 19 '20 at 06:48

1 Answers1

2

std::priority_queue::top() returns a const &, which means you can only call const functions on this reference. Since print does not change the state of the object you should make it const:

//           VVVVV
void print() const {
    std::cout << "name: " << horseName << std::endl;
}

Some unrelated hints:
  • Code like if(someCondition) return true; else return false; can be simplified to return someCondition;
  • operator < should take it's parameter by const & to avoid copying.
  • Check for typos Horse/horse
Lukas-T
  • 11,133
  • 3
  • 20
  • 30