c++ - Sorting an array using a C-style comparator -
i need implement sort function called c. interface looks (and, as or else change it, can't):
typedef int (*comparator )(const void*, const void*, void*); void c_sort(void* ptr, long count, long size, comparatorfunc comp, void* userdata);
i can use c++ implement function, cannot change interface. can see 3 things do:
- write own sort function. sounds bad idea, since we're responsible maintaining it, , difficult implement implementation in either c or c++ standard library without spending 3 weeks or more on it.
- call qsort. problem here comparator takes void* third argument, caller wants pass in implement comparator.
- use std::sort , comparator wrapper around function pointer. favoritest option, because seems easier other three.
in addition, whatever implementation settle on needs thread-safe, can't assign static global pointer userdata , use global pass userdata comparator.
anyway, assuming number 3 go (though i'm open other options), here's question: can pretty set functor wraps function pointer, can't figure out cast void* pointer can call sort.
template<typename t> class comparatorwrapper { public: comparatorwrapper(comparatorfunc comparator, void* userdata) : comparator_(comparator), userdata_(userdata) { } bool operator()(const t& a, const t& b) { return comparator_( reinterpret_cast<void*>(&a), reinterpret_cast<void*>(&b), context) < 0; } private: comparatorfunc comparator_; void* userdata_; };
and call sort should this:
t* foo = reinterpret_cast<t*>(ptr); comparatorwrapper<t> wrapper(comparator, userdata); std::sort(foo, foo+count, wrapper);
the problem don't know t
should be. thing know sizeof(t) == size
. thoughts?
thanks!
Comments
Post a Comment