很久没写 blog 了……大学生活可比高中忙碌多了,哪个混蛋骗我说大学轻松来着……学的东西又难,作业又多,还有学生会活动……啊,我多想回到一中……
最近忙着帮同学写大项目,用 C。话说,对于让没学过编程的人学 C 实在是一件很残酷的事情,即使我现在写仍然觉得很可怕……不过写着写着,觉得 C 实在是一个很神奇的语言,指针和宏是如此的优美~
下面贴两个我在写那项目的时候用到的宏:
1 2 3 4 5 6 7 | #define EXPAND_SPACE(type, p, num, max) { \
if ((num) + 1 >= (max)) { \
if ((max) < 16384) (max) <<= 1; \
else (max) += 512; \
(p) = (type*)realloc((void*)(p), (max)); \
} \
} |
这个是我用来动态扩充空间用的宏,可以非常方便的动态增加需要的空间,这样就不需要为应该预分配多少空间烦恼了~
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 | #define SORT_RESULT(name, type, get, cmp, c1, c2) \ void SortResult_##name(int l, int r, Row **rows, int start) { \ int i = l, j = r; \ type m = get(rows[(i+j)/2], start); \ Row *tmp; \ \ do { \ while ((cmp)(m, get(rows[i], start)) c1 0) ++i; \ while ((cmp)(m, get(rows[j], start)) c2 0) --j; \ if (i <= j) { \ tmp = rows[i], rows[i] = rows[j], rows[j] = tmp; \ ++i, --j; \ } \ } while (i <= j); \ \ if (i < r) SortResult_##name(i, r, rows, start); \ if (l < j) SortResult_##name(l, j, rows, start); \ } #define SORT_RESULT_CHAR(name, c1, c2) \ SORT_RESULT(Char##name, char*, GET_CHARS, strcmp, c1, c2) #define SORT_RESULT_FLOAT(name, c1, c2) \ SORT_RESULT(Float##name, float, GET_FLOAT, MyNumCmp, c1, c2) SORT_RESULT_CHAR ( Asc, >, <) SORT_RESULT_CHAR (Desc, <, >) SORT_RESULT_FLOAT( Asc, >, <) SORT_RESULT_FLOAT(Desc, <, >) |
这个很明显是快排~出于效率考虑,我不得不写4个排序……可是我觉得这样非常不好,代码重用性太低了,就写了个宏,就像上面那样~很偷懒吧~
Comments