Search code examples
c++lambdasetfunctormultiset

Why must I use a const& parameter when defining a functor for STL?


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});

However, if I add const or remove the & for the two parameters of cmp, it will work.

Why can't I use a non-const reference for cmp when I try to insert elements into mt?


Solution

  • According to cppreference, cmp must meet the requirements of Compare.

    Compare's reference says:

    As with any BinaryPredicate, evaluation of that expression is not allowed to call non-const member functions of the dereferenced iterators.

    In order to prevent comparers to unexpectedly change the stored elements' state, you need to either use a const reference or to take the values by copy.