Shrinking An Array After Creation
When I originally posted, it was while developing my mesh class where some models could have 5000 vertices and others only 20. I wanted to be able to get rid of those extra 4980 vertices (each containing three floats) to free up memory in the computer. I'm getting into BlitzMax more now so I may just use that where I can use slices to shrink arrays like this:
Code:
myArray = myArray[..myArray.length-1]
Your mesh class could also have had this:
std::vector<Vertex> vertices;
On init you could specify the exact number of vertices you'd need, or you could max it out to begin with:
vertices.resize(5000);
And when you want to chop off the extras:
vertices.resize(vertices.size() - 1);
STL is hella nice.
(disclaimer: that's all off the top of my head, I think the method names are right...)
std::vector<Vertex> vertices;
On init you could specify the exact number of vertices you'd need, or you could max it out to begin with:
vertices.resize(5000);
And when you want to chop off the extras:
vertices.resize(vertices.size() - 1);
STL is hella nice.

(disclaimer: that's all off the top of my head, I think the method names are right...)
Allow me to second STL. If you're writing in C++ and aren't using STL, you're wasting your time, and are probably creating more subtle bugs than you can shake a stick at.
OneSadCookie Wrote:I think you mean "much less memory-efficient than arrays".
I mean that if you know you're going to have somewhere between 0 and 10000 items, and you end up with only 100 items, a linked list will have a smaller memory footprint than an array of length 10000.
That's certainly true, but if you want an array with somewhere between 0 and 10000 items the last thing you would do would be allocate space for 10000 and waste 99% of it.
As others have pointed out, C++ provides std::vector, but doing something in C with realloc is dead easy too.
As others have pointed out, C++ provides std::vector, but doing something in C with realloc is dead easy too.
Possibly Related Threads...
Thread: | Author | Replies: | Views: | Last Post | |
memcpy(stuct array pointer struct array point) | unknown | 22 | 17,943 |
Sep 29, 2005 03:16 PM Last Post: unknown |