Last active
December 17, 2020 19:07
-
-
Save heatblazer/aafafcac51e0bcc5dd761825df2eae7c to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
a simple example of std::accumulate implemented in C | |
*/ | |
#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); | |
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; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment