【问题标题】:printing a priority queue of objects in c++在 C++ 中打印对象的优先级队列
【发布时间】:2020-07-19 04:56:41
【问题描述】:

我正在尝试打印优先级队列,但它给了我以下错误:

[错误] 将 'const value_type {aka const Horse}' 作为 'void Horse::print()' 的 'this' 参数传递会丢弃限定符 [-fpermissive]

这是我的代码的布局方式:

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

这就是我使用它的方式:

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

}

我的预期输出应该是根据我的 horse 结构中 win 变量的顺序打印马名。

编辑:我的重载运算符正确吗? 我在下面的 cmets 的另一个线程上看到他们将其写为:

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

  return false;
}

【问题讨论】:

  • 尝试在该线程stackoverflow.com/questions/19535644/…中提到的类之外声明运算符
  • 下一次,请尝试编写一个重现您的问题的最小示例。这个过程通常会让你自己发现问题,但也为我们读者省去了阅读和理解其余代码的麻烦。此外,您应该在问题(或答案)中格式化您的代码,并使用适当的缩进使其可读。

标签: c++


【解决方案1】:

std::priority_queue::top() 返回一个const &amp;,这意味着您只能在此引用上调用const 函数。由于print 不会更改对象的状态,因此您应该将其设置为const

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

一些不相​​关的提示:
  • 类似if(someCondition) return true; else return false;的代码可以简化为return someCondition;
  • operator &lt; 应该使用 const &amp; 的参数以避免复制。
  • 检查拼写错误Horse/horse

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-09-16
    • 2017-06-13
    • 1970-01-01
    • 2012-09-23
    • 2011-12-20
    • 1970-01-01
    • 1970-01-01
    • 2016-04-13
    相关资源
    最近更新 更多