c++ - 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 compile 2 lines above, work. // if try insert elements below, i'll errors. //mt.insert({0, 3}); //mt.insert({1, 1}); 

however, if add const or remove & 2 parameters of cmp, work.

why can't use non-const reference cmp when try insert elements mt?

according cppreference, cmp must meet requirements of compare.

compare's reference says:

as binarypredicate, evaluation of expression not allowed call non-const member functions of dereferenced iterators.

in order prevent comparers unexpectedly change stored elements' state, need either use const reference or take values copy.


Comments