william_
william_

Reputation: 1133

printing a priority queue of objects in c++

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

Upvotes: 0

Views: 667

Answers (1)

Lukas-T
Lukas-T

Reputation: 11340

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

Upvotes: 2

Related Questions