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?
bind()?operator()so that it can be used as function. That's called a functor. In C++11 you can create such a beast on the fly, as a "lambda". In C++98/03 you have to either define a class for it, or use some third party library such as Boost. E.g. you can useboost::bindto have a pointer to yourwords, passed to your real function. Cheers & hth.,