In college when I learnt data structures, I was taught to embed the element in the data structure (list)
struct x {
struct x *next, *prev;
int element;
};
But I soon realized that I did not always want "int" as the type of the element, so I learnt the magical type void *
Here is another way to achieve the same thing
struct list {
struct list *next, *prev;
};
struct y {
int element;
struct list l;
};
This way, I could embed the list in anything without building any type information in list. Cool right?
If tomorrow I decided to use a tree, I could simply change
struct y {
int element;
struct tree t;
};
This way the impact on my code for "y" is minimal. In the traditional approach, I would have to use
struct tree xt {
int element;
struct tree *left, *right;
};
and redo most of the code.
The moral of the story
Embed the data structure in the data type and not the other way around
2 comments:
Hi, (Post Deleter :-))
It is not really abstraction. Its a bit complicated, it is more like embedding the data structure.
For example consider an embedded list
struct abc {
...
list_t head;
...
};
I use the head member for all list addition, for example
add_to_list(&ptr->head);
but given head to get back to ptr, I need address magic
(address of head - offset of head) to get back to ptr.
of-course, such things are a little less reliable as they require 100% attention while coding :-)
Post a Comment