【问题标题】:std::priority_queue<struct with const member&> - 'operator =' function unavailablestd::priority_queue<struct with const member&> - 'operator =' 函数不可用
【发布时间】:2018-11-16 02:36:00
【问题描述】:

我正在尝试将具有 const 成员的结构添加到 priority_queue。
这是一个最小的例子:

#include <queue>

struct A
{
    A(const int& i)
        : m_i(i)
    {
    }
    bool operator<(const A& other) const
    {
        return m_i < other.m_i;
    }
    const int& m_i;
};

int main()
{
    std::priority_queue<A> q;
    int i = 3;
    const int& f = i;
    q.emplace(f);
    return 0;
}

我理解这个错误

错误 2 错误 C2582: 'operator =' 函数在 'A' c:...\algorithm 2322 中不可用

我的 A 没有 operator= 重载,因为它不能因为 const int& i。

我有办法让它工作吗?

成员必须是引用,并且只能在此引用上调用 const 函数,但我不介意结构中的值是否更改。

我尝试使用 int& const m_i 并实现 operator=,但我无法使用 const int 参数初始化 emplace(而且我可能不太了解 & const 与 const& 的区别)。

【问题讨论】:

  • 常量引用不存在。你想要一个指向 const 的指针。
  • 我开始想这么多,你有什么原因吗?谷歌只是显示我通过 const ref 链接(而不是引用到 const)
  • @turoni 人们在表示“对 const 的引用”时使用“const 引用”。没有“const 引用”(字面意思),因为引用是不可修改的(不能用来引用另一个对象),所以 const 限定符没有意义。
  • @turoni 不。您正在更改引用的对象。
  • @turoni std::cout &lt;&lt; a &lt;&lt; std::endl 现在将打印6c 是对对象 a 的引用。语句c=b 更改了引用的对象a,但不会导致c 引用另一个对象

标签: c++ c++11


【解决方案1】:

你可以使用间接来解决这个问题。 (优先级)队列要求元素是可分配的。指针是可分配的。因此,队列可以保存指向A 对象的指针,而不是保存不可分配的A 对象。您可能希望队列拥有元素,在这种情况下,您应该使用智能指针(代价是为每个元素分配单独的内存)。示例:

std::priority_queue<std::unique_ptr<A>> q;
q.push(std::make_unique<A>(f));

另一方面,您可以通过使用指针代替引用轻松地使A 可赋值。我建议您考虑一下拥有参考成员是否真的是一个明智的要求。由于某些原因会迫使您参考,std::reference_wrapper(也是可分配的)可能就足够了。

【讨论】:

  • 简单直接的解决方案谢谢。我将使用指向 A 解决方案的指针,我只是在尝试类似但不必要的更复杂的东西(带有 A 指针的自定义包装器类型:p)
猜你喜欢
  • 2022-08-03
  • 1970-01-01
  • 1970-01-01
  • 2020-01-31
  • 1970-01-01
  • 2015-12-16
  • 2017-09-15
  • 1970-01-01
  • 2022-08-23
相关资源
最近更新 更多