尝试在多集中插入元素时出现 C++11 编译错误
C++11 complie error when try to insert element in multiset
代码如下
#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*
代码看起来很适合我,这个问题真的让我很困惑。
你的 compare
函数不应该改变它比较的元素,所以通过 const&
:
获取参数
static bool compare(const shared_ptr<Quote> &l, const shared_ptr<Quote> &r) {
return l->getnum() < r->getnum();
}
代码如下
#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*
代码看起来很适合我,这个问题真的让我很困惑。
你的 compare
函数不应该改变它比较的元素,所以通过 const&
:
static bool compare(const shared_ptr<Quote> &l, const shared_ptr<Quote> &r) {
return l->getnum() < r->getnum();
}