【问题标题】:Use class method comparator on std::sort [duplicate]在 std::sort 上使用类方法比较器 [重复]
【发布时间】:2011-12-17 08:11:03
【问题描述】:

可能重复:
problem sorting using member function as comparator

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

例如:

std::sort(list.begin(),list.end(),object->comparator) //Doesn't compile

如果是,我该怎么做?

【问题讨论】:

  • 是否可以为您的班级定义operator<
  • 已经定义operator ()

标签: c++ oop sorting methods std


【解决方案1】:

您需要将函数作为回调提供:

std::sort(list.begin(),list.end(),object::comparator)

假设你的函数已经是static,我没有看到任何其他问题。

【讨论】:

  • 同意静态,但非静态方法呢?
  • @Vik 查看可能重复发布的链接。
【解决方案2】:

是的,你可以使用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";
}

【讨论】:

  • 这应该是公认的答案,因为它...回答了问题
  • 您需要来自&amp;S::Compare&amp; 吗?我通常自己把它放在那里,因为我确信这样做并没有错,但我只是好奇,因为我看到了在没有 &amp; 的情况下传递函数指针的例子。
  • @gred - Empirically, yes。我没有方便的标准章节,但我想这是因为&amp;S::Compare 不是 指向函数的指针。它是一个指向成员函数的指针,一个完全不同的野兽。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-12-13
  • 2012-05-26
相关资源
最近更新 更多