在std :: sort上使用类方法比较器

Vik*_*Vik 1 c++ sorting oop methods std

可能重复:
使用成员函数作为比较器排序问题

是否可以在std :: sort中使用类方法作为比较器函数?

例如:

std::sort(list.begin(),list.end(),object->comparator) //Doesn't compile
Run Code Online (Sandbox Code Playgroud)

如果是的话,我是怎么做到的?

Rob*_*obᵩ 6

是的,你可以使用boost::bind:

#include <iostream>
#include <algorithm>
#include <iterator>
#include <boost/bind.hpp>

struct S {
  bool ascending;
  bool Compare(int lhs, int rhs) {
    return ascending ? (lhs < rhs) : (rhs < lhs);
  }
};

int main () {

  int i[] = { 1, 3, 5, 7, 8, 6, 4, 2 };
  S s;
  s.ascending = true;
  std::sort(i, i+8, boost::bind(&S::Compare, &s, _1, _2));
  std::copy(i, i+8, std::ostream_iterator<int>(std::cout, " "));
  std::cout << "\n";

  s.ascending = false;
  std::sort(i, i+8, boost::bind(&S::Compare, &s, _1, _2));
  std::copy(i, i+8, std::ostream_iterator<int>(std::cout, " "));
  std::cout << "\n";
}
Run Code Online (Sandbox Code Playgroud)