Talk:K-d tree: Difference between revisions
Content added Content deleted
(+ notes on C entry) |
(→C Entry: stylistic things) |
||
Line 43: | Line 43: | ||
kd_node_t *right; |
kd_node_t *right; |
||
};</lang> |
};</lang> |
||
: 1) In terms of decoupling struct defs and usage, the easiest thing is probably |
|||
:<lang c>void swap(struct kd_node_t *x, struct kd_node_t *y) |
|||
{ |
|||
struct kd_node_t tmp; |
|||
tmp = *x; |
|||
*x = *y; |
|||
*y = tmp; |
|||
}</lang> which hides the details best, but does unnecessary copying. Another way is |
|||
:<lang c>struct point_t { double x[3]; } |
|||
struct kd_node_t { |
|||
point_t pt; |
|||
struct kd_node_t *left, *right; |
|||
} |
|||
void swap(struct kd_node_t *x, struct kd_node_t *y) |
|||
{ |
|||
point_t tmp; |
|||
tmp = x->pt; |
|||
x->pt = y->pt; |
|||
y->pt = tmp; |
|||
}</lang> which is arguably better, because it now allows the compiler to figure out the best method to do the copying. The thing is, hiding details from <code>swap()</code> is not right. Being a performance critical part, it ''should'' know the inner working of the struct involved. You could also argue that one shouldn't do <code>node->x[1]</code>, instead some accessor method <code>get_node_coord(node, 1)</code> should be used. If we were designing a library and plan for it to be used by total strangers who need an interface decoupled from data definition, maybe; for a short example on RC and a samll routine used internally, no. |
|||
: 2) I'm ambivalent towards use of <code>NULL</code> token (it's probably <code>#define NULL (0)</code> anyway), which is better than what I have to say about <code>TRUE</code> or <code>FALSE</code>. If one is reading C code, he better know what a nul pointer is anyhow. I prefer writing <code>0</code>, but won't mind if someone changes it to <code>NULL</code>. |
|||
: 3) The <code>typedef</code> is indeed unneeded. My habit is <code>typedef struct {} sometype_t</code> and <code>typedef struct {} *sometype</code>, where <code>_t</code> says it's a struct, and lacking of it means a pointer. This may make pointers to pointers easier to write (<code>sometype *p</code> instead of <code>sometype_t **p</code>), but is certainly not necessary. I'll drop the <code>typedef</code>s here, but I doubt it will make the code more or less readable. --[[User:Ledrug|Ledrug]] 21:34, 26 April 2012 (UTC) |