gpt4 book ai didi

c++ - 尝试在多集中插入元素时发生C++ 11编译错误

转载 作者:行者123 更新时间:2023-12-02 10:22:07 25 4
gpt4 key购买 nike

代码如下

#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);将导致complie错误。编译错误如下
*/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*

代码对我来说很合适,这个问题确实让我感到困惑。

最佳答案

您的compare函数不应更改要比较的元素,因此请使用const&接受参数:

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

Demo

关于c++ - 尝试在多集中插入元素时发生C++ 11编译错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59622299/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com