【发布时间】:2020-03-12 15:44:23
【问题描述】:
struct Heap {
int capacity;
int heapSize;
int *tree; // the heap binary tree
int *pos; // pos[i] is the position of values[i] in items
float *p; // priority value of each heap element
};
void initHeap(struct Heap *heap, int capacity) {
heap->capacity = capacity;
heap->heapSize = 0;
heap->tree = malloc(sizeof(int)*(capacity+1));
heap->pos = malloc(sizeof(int)*(capacity+1));
heap->p = malloc(sizeof(float)*(capacity+1));
}
void betterInit(struct Heap *heap, int capacity) {
with (heap) { // doesn't exist
capacity = capacity;
heapSize = 0;
tree = malloc(sizeof(int)*(capacity+1));
pos = malloc(sizeof(int)*(capacity+1));
p = malloc(sizeof(float)*(capacity+1));
}
}
// update heap after a value is increased
void upHeap(struct Heap *heap, int i) {
int *tree = heap->tree, *pos = heap->pos;
float *p = heap->p;
int c, r;
c = pos[i]; // position of element i-th in heap
while (true) {
r = parent(c);
if (r==0 || p[tree[r]] >= p[i]) break; // if c is root, or priority(parent(c)) is > priority(c)
pos[tree[r]] = c; // pull the parent down to c
tree[c] = tree[r];
c = r;
}
tree[c] = i;
pos[i] = c;
}
所以第一个initHeap 看起来很长,因为我必须写很多次heap->。我想让它看起来更短。
一种解决方案是这样写:
int *tree = heap->tree;
int *pos = heap->pos;
float *p = heap->p;
然后使用tree, pos, p。还有更多方法吗?
【问题讨论】:
-
抱歉,C 对此没有任何快捷方式。
-
您当前的
initHeap对我来说看起来非常好、可读且惯用。 -
哦,真可惜 :( @NateEldredge 它看起来不错,直到像 heap->tree[heap->pos[i]]
-
如果你想要Pascal,你可以使用它。不过,即使在 Pascal 中,
with子句也会令人困惑。 -
请注意,
capacity = capacity;行仅表示如果with子句可用时会出现的问题之一 — 是heap->capacity = capacity;或capacity = heap->capacity;或heap->capacity = heap->capacity;或capacity = capacity;?答案是编译器无法判断 — 必须更改代码,也许参数是cap而不是capacity。它很快就会变得一团糟!
标签: c pointers struct pass-by-reference