Re: [solved] polymorphic sorting functors
L. Kliemann schrieb:
* Thomas J. Gritzan <phygon_antispam@gmx.de>:
If you want to change the sorting behaviour at run-time, you could pass
a tr1::function object to std::sort.
Great! I'd never heard of tr1 before, but it seems to be a solution.
tr1 will be part of the coming C++ standard. Most parts of it were
developed and were/are part of the Boost library. Both tr1 and Boost are
worth to know.
This code works (using gcc 4.2.4, produced no warnings with -Wall and
-Wextra):
Some comments:
#include <iostream>
#include <vector>
#include <algorithm>
#include <tr1/functional>
using namespace std;
typedef tr1::function <bool (int, int)> func_t;
class cmp_base : public std::binary_function<int, int, bool> {
public:
virtual bool operator()(int i, int j) = 0; };
class cmp_inc : public cmp_base {
public:
virtual bool operator()(int i, int j) { return i<j; } };
class cmp_dec : public cmp_base {
public:
virtual bool operator()(int i, int j) { return i>j; } };
You don't need a hierarchy with virtual functions. You can contruct a
tr1::function object with a simply functor (class with operator()) or
even a normal function. tr1::function works internally with virtual
functions and will dispatch the call to the currently assigned function
or functor.
But be aware that this run-time dispatch will disable some compiler
optimization, like inlineing the comparator function into the sort
algorithm. It's not a problem unless you have many objects to sort and
you need speed.
void sort_it(vector<int> *v, func_t cmp) {
sort(v->begin(), v->end(), cmp); }
Prefer pass by reference:
void sort_it(vector<int>& v, const func_t& cmp) {
sort(v.begin(), v.end(), cmp);
}
Pointers have additional complexity that's not needed in this case.
Pointers can be null, they can be reseated, you can do arithmetics with
them. Prefer to use pointers only when you need them.
I would also pass the comparator by (const) reference to avoid a copy.
It is a kind of microoptimization, but a common one.
int main(void) {
vector<int> v;
v.push_back(10);v.push_back(1);v.push_back(20);
cmp_dec cmp1;
sort_it(&v, cmp1);
cout << "decreasing:" << endl;
for (unsigned int i=0; i<v.size(); ++i) { cout << v.at(i) << endl; }
cmp_inc cmp2;
sort_it(&v, cmp2);
cout << "increasing:" << endl;
for (unsigned int i=0; i<v.size(); ++i) { cout << v.at(i) << endl; }
return 0; }
In general, if you want others to read your code, please insert more
whitespace/newlines. This code might be compact formatted, but it is
horrible to read it.
--
Thomas