Class:
Class:
private:
...
vector<string> words;
vector< list<int> > vints;
public:
myFunction(...)
I am calling a sort on non-empty list in another member function:
void myClass::myFunction (...) {
...
if (!vints[i].empty()) vints[i].sort(sortFunc);
...
}
My sorting function:
bool myClass::sortFunc(const int& i, const int& j) { return (words[i] < words[j]); }
The Error:
error: no matching function for call to ‘std::list<int, std::allocator<int> >::sort(<unresolved overloaded function type>)’
/usr/include/c++/4.4/bits/list.tcc:301: note: candidates are: void std::list<_Tp, _Alloc>::sort() [with _Tp = int, _Alloc = std::allocator<int>]
/usr/include/c++/4.4/bits/list.tcc:378: note: void std::list<_Tp, _ Alloc>::sort(_StrictWeakOrdering) [with _StrictWeakOrdering = bool (SuperWordSearch::*) (const int&, const int&), _Tp = int, _Alloc = std::allocator<int>]
I have researched and come across the following questions:
C++ Custom compare function for list::sort
Problem sorting a list of pointers
Error in std::list::sort with custom comparator (expected primary-expression before ')' token)
and they would have been sufficient had it not been for the fact that in this class, the sortFunc depends on the member variable WORDS for that instance of the object. So I cannot make the comparator function (sortFunc) static or global
EDIT: Just came across this How to sort a std:list when you need member data? and it provides a solution by making a friend class, but is it possible to accomplish this inside the user-defined class itself?
With lambdas:
vints[i].sort([&words](int i, int j) { return words[i] < words[j]; });
With std::bind
:
#include <functional>
//...
{
using namespace std::placeholders;
vints[i].sort(std::bind(&myClass::sortFunc, this, _1, _2));
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With