C++std列表排序使用自定义比较器,该比较器依赖于对象实例的成员变量

C++ std list sort with custom comparator that depends on an member variable for the object instance

本文关键字:比较器 对象 依赖于 实例 变量 成员 排序 列表 自定义 C++std      更新时间:2023-10-16

类别:

Class:
  private:
    ...
    vector<string> words; 
    vector< list<int> > vints;
  public:
    myFunction(...)

我正在调用另一个成员函数中的非空列表排序:

void myClass::myFunction (...) {
    ...
    if (!vints[i].empty()) vints[i].sort(sortFunc);
    ...
}

我的排序功能:

bool myClass::sortFunc(const int& i, const int& j) { return (words[i] < words[j]); }

错误:

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>]

我研究并遇到了以下问题:

C++自定义列表比较功能:排序

排序指针列表时出现问题

使用自定义比较器进行std::list::排序时出错(应为';之前的主表达式(';代币(

如果不是因为在这个类中,sortFunc依赖于对象实例的成员变量WORDS,它们就足够了。所以我不能使比较器函数(sortFunc(静态或全局

编辑:刚刚遇到这个问题。当你需要成员数据时,如何对std:list进行排序?它通过创建一个友元类提供了一个解决方案,但有可能在用户定义的类内部实现这一点吗?

带lambdas:

vints[i].sort([&words](int i, int j) { return words[i] < words[j]; });

std::bind:

#include <functional>
//...
{
  using namespace std::placeholders;
  vints[i].sort(std::bind(&myClass::sortFunc, this, _1, _2));
}

@Kerrek涉及lambdas的答案更好。但是,如果必须避免C++11的特性,那么用函子替换排序函数。允许该函数存储对所需数据的引用,如下所示:

#include <vector>
#include <list>
#include <string>
class myClass {
private:
  std::vector<std::string> words;
  std::vector<std::list<int> > vints;
  // Instead of sortFunc, use sortFunctor. A functor can be used in place 
  // of a function in many places, and it can carry state (like a reference
  // to the data it needs).
  struct sortFunctor {
    const std::vector<std::string>& words;
    sortFunctor(const std::vector<std::string>& words) : words(words) { }
    bool operator()(int i, int j) { return words[i] < words[j]; }
  };
public:
  void myFunction() {
    vints[0].sort(sortFunctor(words));
  }
  myClass() {
    words.push_back("apple");
    words.push_back("berry");
    std::list<int> l;
    l.push_back(0);
    l.push_back(1);
    vints.push_back(l);
  }
};
int main () {
  myClass object;
  object.myFunction();
}