Re: polymorphic sorting functors
On Jun 19, 12:02 pm, "L. Kliemann" <stu33...@mail.uni-kiel.de> wrote:
#include <iostream>
#include <vector>
using namespace std;
class cmp_base : public std::binary_function<int, int, bool> {
public:
virtual bool operator()(int i, int j) { return i>j; }};
class cmp_inc : public cmp_base {
public:
virtual bool operator()(int i, int j) { return i<j; }};
void sort_it(vector<int> *v, cmp_base *cmp) {
sort(v->begin(), v->end(), *cmp);}
int main(void) {
vector<int> v;
v.push_back(10);v.push_back(1);v.push_back(20);
cmp_inc cmp;
sort_it(&v, &cmp);
for (unsigned int i=0; i<v.size(); ++i) { cout << v.at(i) << end=
l; }
return 0;
}
It should be clear what I am trying to implement here: function sort_it s=
hall
sort the given vector according to the comparison functor passed in the
second argument. The base class 'cmp_base' would usually be implemented
purely virtual, but is here given with an implementation for sorting the
vector in decreasing order, for demonstration purposes.
The problem is that although I create an object of type 'cmp_inc', the ve=
ctor
is sorted in decreasing order. If 'cmp_base' is implemented as an ABC, th=
e
program won't even compile.
As far as I understood, I am following a standard approach here: having a
base class and functions taking pointers to the base class, but in fact
handing pointers to objects of derived classes to these functions. Howeve=
r,
the sort function from the STL expects an object, not a pointer, and so I
pass *cmp to it. This seems to be the cause of all the trouble.
Is there still a way to do this without using templates?
It seems std::sort takes the 3rd parameter as a pass by value not a
pass by reference.
Therefore when you pass a reference to a cmp_base by value into
std::sort, std::sort has no idea about the derived object type you are
actually passing.
Makes sense?
Ivan Novick