I've come up with some simple implementation for algorithms in C
and more specifically for std::accumulate
alternate since I need something like it recently. Can you provide some review on the approach?
#include <stdio.h>
#include <string.h>
#define ARRSIZE(X) (sizeof(X) / sizeof(X[0]))
#define ACCUMULATE(RET, FIRST, LAST, INIT, SUM_CB) \
do { \
RET = INIT; \
while (FIRST != LAST){ \
RET = SUM_CB(RET, *FIRST); \
FIRST++; \
} \
} while(0);
/**
* example usage
* sum integers and sum strings by some delimiter
*/
struct str_t
{
char data[512];
};
struct str_t sumStr(struct str_t a, struct str_t b)
{
struct str_t ret = {0};
strcat(ret.data, a.data);
strcat(ret.data, "--");
strcat(ret.data, b.data);
return ret;
}
struct A { int a, b, c; };
struct A sumA(struct A a, struct A b) {
struct A ret ;
ret.a = a.a + b.a;
ret.b = a.b + b.b;
ret.c = a.c + b.c;
return ret;
}
int main()
{
unsigned long i;
struct A sumvec[10];
struct str_t sumstr[10];
memset(sumstr, 0, sizeof(sumstr));
for(i=0; i < ARRSIZE(sumvec); i++) {
sumvec[i].a = i;
sumvec[i].b = i+1;
sumvec[i].c = i+2;
snprintf(sumstr[i].data, sizeof(sumstr[i].data), "%d", i);
}
for(i=0; i < ARRSIZE(sumvec); i++) {
printf("[%d][%d][%d]\r\n", sumvec[i].a ,sumvec[i].b,sumvec[i].c);
}
struct A ret = {sumvec[0].a, sumvec[0].b, sumvec[0].c};
struct A* pBegin = &sumvec[1];
struct A* pEnd = &sumvec[ARRSIZE(sumvec)];
ACCUMULATE(ret, pBegin, pEnd, ret, sumA)
printf("SUM: [%d][%d][%d]\r\n", ret.a, ret.b, ret.c);
struct str_t retstr;
strcat(retstr.data, sumstr[0].data);
struct str_t *pBegs = &sumstr[1];
struct str_t *pEnds = &sumstr[ARRSIZE(sumstr)];
ACCUMULATE(retstr, pBegs, pEnds, retstr, sumStr);
printf("SUM STR: [%s]\r\n", retstr.data);
return 0;
}