为什么我必须使用const&为STL定义仿函数时的参数?

时间:2016-09-02 09:12:35

标签: c++ lambda set functor multiset

auto cmp = [](pair<int, int> & left, pair<int, int> & right){if(left > right) return true; else return false;};
multiset<pair<int, int>, decltype(cmp)> mt(cmp);
// If I just compile the two lines above, it will work.
// But if I try to insert some elements as below, I'll get errors.
//mt.insert({0, 3});
//mt.insert({1, 1});

但是,如果我为const的两个参数添加&或删除cmp,则会有效。

当我尝试将元素插入const时,为什么我不能对cmp使用非mt引用?

2 个答案:

答案 0 :(得分:2)

根据cppreference,cmp must meet the requirements of Compare

Compare的参考说:

  

与任何BinaryPredicate一样,不允许对该表达式的求值调用解除引用的迭代器的非const成员函数。

为了防止比较器意外更改存储元素的状态,您需要使用const引用或通过复制获取值。

答案 1 :(得分:0)

编译器认为您可以更改传递给cmp函数的参数,因为您已为输入参数指定了引用。但是,您拥有的insert语句是传递无法修改的常量(并且编译器知道这一点)。因此不匹配。

如果你分配了两个变量,然后将变量传递给你的insert(),那么它有效吗?