enc*_*097 4 c++ sorting list std
类:
Class:
private:
...
vector<string> words;
vector< list<int> > vints;
public:
myFunction(...)
Run Code Online (Sandbox Code Playgroud)
我在另一个成员函数中调用非空列表中的排序:
void myClass::myFunction (...) {
...
if (!vints[i].empty()) vints[i].sort(sortFunc);
...
}
Run Code Online (Sandbox Code Playgroud)
我的排序功能:
bool myClass::sortFunc(const int& i, const int& j) { return (words[i] < words[j]); }
Run Code Online (Sandbox Code Playgroud)
错误:
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>]
Run Code Online (Sandbox Code Playgroud)
我研究过并遇到过以下问题:
std :: list :: sort中的错误与自定义比较器(''之前的预期primary-expression')令牌)
如果不是因为在这个类中,sortFunc依赖于该对象实例的成员变量WORDS,那么它们就足够了.所以我不能使比较器函数(sortFunc)静态或全局
编辑:刚刚遇到这个如何在需要成员数据时对std:list进行排序?它通过创建友元类提供了一个解决方案,但是可以在用户定义的类本身内完成吗?
使用lambdas:
vints[i].sort([&words](int i, int j) { return words[i] < words[j]; });
Run Code Online (Sandbox Code Playgroud)
用std::bind:
#include <functional>
//...
{
using namespace std::placeholders;
vints[i].sort(std::bind(&myClass::sortFunc, this, _1, _2));
}
Run Code Online (Sandbox Code Playgroud)