I was trying to sort a Map by value , using the std::sort and a custom compare function. But I got a compile error .
I don't know how to use Lambda functions. I just know they can be used. But for now I need to learn what went wrong with the custom compare function.
I have already tried using iterator variables as arguments in the dcompare function.
class Solution {
public:
int foo(int n) {
unordered_map<int,int> M ;
// Inputs = {2,4,5,2,4,2,1}
M[4] = 2;
M[5] = 1;
M[2] = 3;
M[1] = 1;
for(auto it : M){
cout<<it.first<<" : "<<it.second<<endl;
}
sort(M.begin(), M.end(), dcompare);
for(auto it : M){
cout<<it.first<<" : "<<it.second<<endl;
}
return 0;
}
private:
static bool dcompare(const std::pair<int,int> itL, const std::pair<int,int> itR) {
return (itL.second < itR.second);
}
};
/*
I get the same error when I changed the variables to iterators
static bool dcompare(const map<int,int>::iterator itL, const map<int,int>::iterator itR)
{
return (itL->second < itR->second);
}
*/Compile error:
/usr/local/include/c++/8.2.0/bits/stl_algo.h: In instantiation of 'void std::__sort(_RandomAccessIterator, _RandomAccessIterator, _Compare) [with _RandomAccessIterator = std::_Rb_tree_iterator >; _Compare = __gnu_cxx::__ops::_Iter_comp_iter, std::pair)>]': /usr/local/include/c++/8.2.0/bits/stl_algo.h:4866:18: required from 'void std::sort(_RAIter, _RAIter, _Compare) [with _RAIter = std::_Rb_tree_iterator >; _Compare = bool (*)(std::pair, std::pair)]' Line 15: Char 42: required from here /usr/local/include/c++/8.2.0/bits/stl_algo.h:1969:22: error: no match for 'operator-' (operand types are 'std::_Rb_tree_iterator >' and 'std::_Rb_tree_iterator >') std::__lg(__last - __first) * 2,
PS:
I can't share the actual question , So I am sharing just the sorting part of it with some debug prints.