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:

  1. 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.
  2. call qsort. problem here comparator takes void* third argument, caller wants pass in implement comparator.
  3. 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

Popular posts from this blog

database - VFP Grid + SQL server 2008 - grid not showing correctly -

jquery - Set jPicker field to empty value -

.htaccess - htaccess convert request to clean url and add slash at the end of the url -