Tuesday, July 14, 2009

How to resize an array in C++?

Hey, I just need to create a basic resize array method. I'm not sure how to do it though.





int array[ ];


//declare array





I'm thinking....





int size;


int array[ size ];


//Is this the correct way or is this defining another array? Thanks.

How to resize an array in C++?
you need to use dynamic memory (lookup 'new' in your book)
Reply:You probabily don't need to use the new operator, with the large cache sizes on computers, arrays are very efficient. The new operator is dynamic but requires knowledge to use it properly in your program. Things could get messy if your not familiar with employing your own memory management (procedurally allocating/deallocating memory). Great if your program uses a huge amount of memory and needs items sorted by their value. Especially great if you are implementing with an abstract data type.


You don't have to use the new operator but you can't change the size of an array once initialized.


Roughly, what is the largest number of elements your array will hold at any one time? Initialize your array with this value + 5% just in case, but not necessary if you know exactly. Performance will drop on a 8k cache if your array houses millions of elements. Your safe to allocate loads even if unused.
Reply:unless your need for speed is critical, and you assume all array management, you might want to look into the stl collection classes like vector, which is a dynamically growing array.

local florist

No comments:

Post a Comment