【问题标题】:C++11 complie error when try to insert element in multiset尝试在多集中插入元素时 C++11 编译错误
【发布时间】:2020-04-24 14:22:13
【问题描述】:

代码如下

#include <set>
#include <iostream>
#include <string>
#include <memory>

using namespace std;
class Quote {
    public:
        int getnum() {
            return num;
        }
    private:
        int num;
};

class basket {
    public:
        void add_item(const shared_ptr<Quote> &b) {
            setQuo.insert(b);
        }
    private:
        static bool compare(shared_ptr<Quote> &l, shared_ptr<Quote> &r) {
            return l->getnum() < r->getnum();
        }
        multiset<shared_ptr<Quote>, decltype(compare)*> setQuo{compare};
};


int main()
{
    cout << "start" << endl;
}

我发现setQuo.insert(b);会导致编译错误。编译错误如下

*/usr/include/c++/7/bits/stl_tree.h:2069:51: error: binding reference of type ‘std::shared_ptr<Quote>&’ to ‘const key_type {aka const std::shared_ptr<Quote>}’ discards qualifiers
__x = _M_impl._M_key_compare(__k, _S_key(__x)) ?*

*/usr/include/c++/7/bits/stl_tree.h:1750:10: error: binding reference of type ‘std::shared_ptr<Quote>&’ to ‘const std::shared_ptr<Quote>’ discards qualifiers*

代码看起来很适合我,这个问题让我很困惑。

【问题讨论】:

标签: c++ c++11 multiset


【解决方案1】:

您的 compare 函数不应更改它正在比较的元素,因此请使用 const&amp; 的参数:

        static bool compare(const shared_ptr<Quote> &l, const shared_ptr<Quote> &r) {
            return l->getnum() < r->getnum();
        }

Demo

【讨论】:

  • 这是编译错误的原因。非常感谢,你帮了很多忙:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-01-24
  • 2013-10-26
  • 1970-01-01
  • 1970-01-01
  • 2018-09-26
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多