Typo at line 6, leave a space between
new
and
TYPE
.
size = size + 1;
can be written as
++size;
or
size+=1;
for simplicity.
Curly braces not needed when only one instruction is in
for(),
if(),
while() or
do while();.
One bug in your code is that at the end of the
for(), you will copy an element that doesn't exist.
Your code should run fine, but only because you don't modify that element's value.
Secondly you don't sort anything, you just add the new element to the end of the
elements.
Finally, be sure to have a dummy
elements = new TYPE[1];
(in Constructor) before running
insert() for the first time. And obviously, the
delete[] elements;
in the Destructor.
Here you go, my version. It's your business if you learn from it, or just steal it. Good luck.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
|
template <typename TYPE>
void insert(const TYPE &x)
{
int where=0; // where to insert the new element
while (elements[where] < x && where <= size) // find where
++where;
size += 1; // update size
TYPE *temp = new TYPE[size];
temp[where] = x; // add x
for (int i=0; i<where; ++i) // copy first part from elements
temp[i] = elements[i];
for (int i=where+1; i<size; ++i) // copy second part from elements
temp[i] = elements[i];
delete[] elements;
elements = temp;
}
|
Edit: typos.
Edit2: contains some bugs too. Happy hunting.