在std上使用class:sort()

时间:2013-04-24 01:25:16

标签: c++ class sorting vector struct

这里有一个例子: http://www.cplusplus.com/reference/algorithm/sort/

显示

struct myclass {
  bool operator() (int i,int j) { return (i<j);}
} myobject;

int main () {
  int myints[] = {32,71,12,45,26,80,53,33};
  std::vector<int> myvector (myints, myints+8);               // 32 71 12 45 26 80 53 33

  // using object as comp
  std::sort (myvector.begin(), myvector.end(), myobject);     //(12 26 32 33 45 53 71 80)
}

这很好,但是我试图使用类而不是结构。所以我正在做的是:

CardComparer类:

bool CardComparer::operator() (Card* firstCard, Card* secondCard) {
    this->firstCard = firstCard;
    this->secondCard = secondCard;
    if (firstCard->GetRank() == secondCard->GetRank()) {
        return firstCard->GetSuit() > secondCard->GetSuit();
    }
    else {
        return firstCard->GetRank() > secondCard->GetRank();
    }
}

这是主要的:

CardComparer* compare;
compare = new CardComparer();
sort(cards.begin(), cards.end(), compare->operator());

我收到这个长错误:

hand.cpp: In member function 'void Hand::AddCard(Card*)':
hand.cpp:60:54: error: no matching function for call to 'sort(std::vector<Card*>::iterator, std::vector<Card*>::iterator, <unresolved overloaded function type>)'
hand.cpp:60:54: note: candidates are:
In file included from /usr/include/c++/4.7/algorithm:63:0,
                 from hand.cpp:4:
/usr/include/c++/4.7/bits/stl_algo.h:5463:5: note: template<class _RAIter> void std::sort(_RAIter, _RAIter)
/usr/include/c++/4.7/bits/stl_algo.h:5463:5: note:   template argument deduction/substitution failed:
hand.cpp:60:54: note:   candidate expects 2 arguments, 3 provided
In file included from /usr/include/c++/4.7/algorithm:63:0,
                 from hand.cpp:4:
/usr/include/c++/4.7/bits/stl_algo.h:5499:5: note: void std::sort(_RAIter, _RAIter, _Compare) [with _RAIter = __gnu_cxx::__normal_iterator<Card**, std::vector<Card*> >; _Compare = bool (CardComparer::*)(Card*, Card*)]
/usr/include/c++/4.7/bits/stl_algo.h:5499:5: note:   no known conversion for argument 3 from '<unresolved overloaded function type>' to 'bool (CardComparer::*)(Card*, Card*)'

我无法真正找到解决方案,因为如果我修改示例并将其保存为结构,它可以正常工作,但在将其转换为类时不起作用。

1 个答案:

答案 0 :(得分:4)

第三个参数称为仿函数,可以调用。指向函数的指针,C ++ 11 lambda或具有operator()成员函数的对象实例(非指针)。

在你的情况下,不要在堆上动态分配仿函数对象,这足以在std::sort调用中将其声明为临时对象:

std::sort(cards.begin(), cards.end(), CardComparer());

在上面的std::sort调用中,使用CardComparer() 在堆栈上创建对象,此对象是临时的,仅在std::sort运行时有效。 std::sort函数将调用此对象,这与在对象上调用operator()函数相同。

由于此比较函数非常简单,因此无需存储任何数据:

struct CardComparer
{
    bool operator() (const Card* firstCard, const Card* secondCard) const { ... }
};

因此不需要成员数据字段。