General map operation in C -
this question has reply here:
implementing generical 'map' function on arrays in c 3 answershow can define general map operation on array in c?
ideally want python's map(function,array) ~~ macro. believe c++'s std::transform, in c, , not utilize iterators..
(this unary operation) thinking like:
template <class t*, class u*,size_t n> t* map(t (*func)(u), u* arr,size_t n) { t* tmp = (t*)malloc(sizeof(t) * n); size_t i; for(i=0;i<n;i++) { *(tmp+i) = *func(*(arr+i)); } }
... of course of study templates in c++.. how can 1) latter , 2) if could, prepare above code snippet.
thanks
for template this, there straightforward translation macros; major syntactic wrinkle can't homecoming result array, variable write has parameter.
#define map(func_, input_, output_, type_, n_) { \ output_ = xmalloc(sizeof(type_) * (n_)); \ size_t i_; \ (i_ = 0; i_ < (n_); i_++) \ output_[i_] = func_(input_[i_]); \ } while (0)
this not type-unsafe looks, provided pay attending compiler warnings. however, not particularly safe if of actual arguments utilize of macro isn't simple identifier. importantly, catastrophic things happen if of actual arguments has side effects.
this can cured, can inability homecoming result array, if you're willing utilize gnu extensions...
#define gnumap(func_, input_, type_, n_) ({ \ __typeof(func_) func__ = (func_); \ __typeof(input_) input__ = (input_), \ output__ = xmalloc(sizeof(type_) * n__); \ __typeof(n_) n__ = (n_), \ i__; \ (i__ = 0; i__ < n__; i__++) \ output__[i__] = func__(input__[i__]); \ /* homecoming */ output__; \ })
would either of these in real life? not, to the lowest degree bad available option. think of 1 step shy of rewriting critical inner loop in assembly language.
(xmalloc
, in case you're unfamiliar it, conventional name user-written wrapper around malloc
either succeeds or crashes entire program. utilize here dodge question of how cope malloc
failing.)
c
No comments:
Post a Comment