-
Dymanic Array
hei buddies, have more than a month did login this forum :D. "coz juz busy with a project and now I juz stuck in somewhere else and need your expert to get me out from the dark :)
what is the good what to write a dynamic array in C++/VC++? I have to store the following item in the array:
PHP Code:
typedef struct tagLANDMARK
{
TCHAR Place[33];
TCHAR type[33];
long Ptr;
RECT rt;
} LANDMARK;
I use UNICODE here is because the app is running on WinCE and it should not have any significant in coding :)
regards,
Chris.C
-
I think the easiest way to create a dymanic array would be to use the ready-made vector class. Otherwise you'd have to create your own linked-list or binary-tree class.
Code:
vector<int> myVar;
// Add objects to the vector
myVar.push_back(43);
myVar.push_back(466);
myVar.resize(10);
myVar[8] = 43;
-
An array provides instant random access unlike linked lists and trees
A dynamical array is allocated on the heap, and access is provided with a pointer.
allocation:
type* array = new type[elements];
random access:
array[element];
destruction:
delete[] array;
-
Megatron: if he is codeing for WinCE, using vector might not be a good idea...
-
kedaman: While that is a dymanic array, it cannot be resized without losing all the data that was originally in it. (unless you write your own function to loop through the elements and add them to the new array)
-
well thats how you do it usually :p
template <class T>
T* resize(T*& x,int size){T* temp=(T*)memcpy(new T[size],x,_msize(x));delete[]x;return x=temp;}
-
kedaman, you sure know how to make code totally illegible. But it is cool nevertheless - I never thought there's such a cool way to take advantage of the fact that memcpy returns the address of the buffer.
-
readability vs elegance
I prefer elegance, because it's cool, and in some cases like this, also profitable in performance :)
-
yeah, but splitting up the lines wouldn't hurt performance without decreasing performance. But personally I like code that I can read but not newbies :D :p
-