Hi,
I had an idea that in order to keep track of dynamically created objects, it was useful to store their pointers in a container. While, I don't understand containers yet, it is my next point of learning. I understand vectors would be useful for creating objects. But if I decided that my program can delete objects at any time from any position, would using a vector be a wise choice? As this would entail either setting the value to NULL or deleting the item, and I was under the impression you can't delete from the middle of a vector.
Do you have any experience doing this or a suggestion against this method?
Thanks in advance,
(Another stupid question from) LukeyJ
Storing Pointers to Objects in Containers
Started by LukeyJ, Nov 18 2008 02:56 PM
3 replies to this topic
#1
Posted 18 November 2008 - 02:56 PM
|
|
|
#2
Posted 18 November 2008 - 03:38 PM
LukeyJ said:
I had an idea that in order to keep track of dynamically created objects, it was useful to store their pointers in a container. While, I don't understand containers yet, it is my next point of learning. I understand vectors would be useful for creating objects.
LukeyJ said:
But if I decided that my program can delete objects at any time from any position, would using a vector be a wise choice?
LukeyJ said:
As this would entail either setting the value to NULL or deleting the item, and I was under the impression you can't delete from the middle of a vector.
This thread is somewhat related.
#3
Posted 18 November 2008 - 06:07 PM
It will depend on how you need to access the pointers, and the type of work you'll be doing. A linked list of pointers, a set<*T>, or various other containers all come to mind, but they also have different overheads for getting access to the pointer you want.
#4
Posted 18 November 2008 - 07:25 PM
I made a simple solution for this for projectiles in games. I've used this simple code in quite a few games. It's an unordered collection of pointers. There's also an iterator function:
typedef struct {
void ** p;
int len;
int space;
} list;
int list_init(list * l, int siz){
if(l->p = malloc(sizeof(void *) * siz)){
l->space = siz;
l->len = 0;
return 1;
}
return 0;
}
int list_add(list * l, void * v){
if(l->len != l->space){
l->p[l->len] = v;
l->len += 1;
return 1;
}
return 0;
}
int list_del(list * l, int n){
if(n < l->len){
l->len -= 1;
l->p[n] = l->p[l->len];
return 1;
}
return 0;
}
int list_kill(list * l){
free(l->p);
l->space = 0;
l->len = 0;
}
void list_pass(list * l, void (*h)(list *,void *,int)){
int i = 0;
while(i < l->len){
(*h)(l,l->p[i],i);
i++;
}
}
I don't know if that's useful, but it's useful to me. Whatever.


Sign In
Create Account


Back to top









