igraph-help
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: [igraph] Freeing vector's unused space[C]


From: Tamás Nepusz
Subject: Re: [igraph] Freeing vector's unused space[C]
Date: Mon, 30 Sep 2013 18:17:28 +0200

> Consifer this scenario, i have initialized igraph vector(for edges insertion) 
> with 10 elements(igraph_vector_init(&v, 10);)
> but actually assigned(VECTOR[n] = ) only three elements,
> the thing what will happend when i'll actually execute igraph_insert_edges -- 
> that three assigned by me elements
> will point to right vertices but other elements will point to vertex 0 which 
> is understandable.
> What i'm trying to do is to igraph_vector_resize_min(&v) but it does nothing 
> - resul is the same.
Well, igraph_vector_resize_min does not distinguish between elements that you 
have inserted explicitly and elements that were set to zero explicitly when the 
vector was constructed -- the size of the vector is still 10, no matter what 
you do, so igraph_vector_resize_min will not do anything.

> Moreover igraph_vector_size(&v) gives me 10 which i'm assuming vector's 
> capacity in my case and actuall size of vector should be 3.
No; igraph_vector_size is right, the *size* of your vector is 10 and so is its 
capacity. You have constructed a vector with igraph_vector_init(&v, 10), which 
sets its size to 10. If you want to create a vector from which you will use 
only three elements, use igraph_vector_init(&v, 3). If you want to create a 
vector whose final size you do not know in advance, you can simply initialize 
it with zero elements (igraph_vector_init(&v, 0)) and then use 
igraph_vector_push_back to grow the vector as needed and append a new element 
at the end.

Actually, in most cases, you won't need igraph_vector_resize_min() at all. The 
only case when it is needed is when you have a long-lived vector, you know that 
it *used* to hold a lot of elements (but not any more), and you want to release 
the extra memory that the vector is holding on to "just in case". For instance:

/* create a vector with zero elements. v will have size=0 and capacity=0 here */
igraph_vector_init(&v, 0);

/* add 10000 elements to it */
for (i = 0; i < 10000; i++) {
    igraph_vector_push_back(&v, i);
}

/* now v has a size of 10000 elements and a capacity that is slightly larger 
than that (to avoid having to re-allocate the vector every time a new element 
is added to it */

/* let us now clear the vector */
igraph_vector_resize(&v, 0);

/* at this point, v has a size of zero, but its capacity is still more than 
10000 elements since it *used* to be that large. If you want to free the memory 
associated to the vector, you can call igraph_vector_resize_min now */
igraph_vector_resize_min(&v);

-- 
T.




reply via email to

[Prev in Thread] Current Thread [Next in Thread]