0

I have an array of pointers on my class which I need to sort. Sorting is working correctly, Im just not sure, whether Im switching just reference on class, or the whole class...

My code is like:

ITEM *items = new ITEM[set.pathc];
...
bool change = true;
while( change )
{
change = false;
for( i = 0; i < set.pathc-1; i++ )
{
    if( compare( items+i, items+i+1, set.order, set.order_asc ) )
    {
        ITEM temp;
        temp = *(items+i);
        items[i] = items[i+1];
        items[i+1] = temp;

        change = true;
    }
}
}

So is my code switching just pointers (I mean adresses of where the object is allocated) or the whole objects (like copying all of the private variables, wouldn't it need "=" operator for this?) ?

I want to switch just pointers because I guess it would be much more faster, I tried it like this

ITEM *temp
temp = item+i;
item[i] = item+i+1;
item[i+1] = temp;

but it didnt work :-/ (I couldnt even compile the code)

thanks in advance for explaining :)

Buksy
  • 11,571
  • 9
  • 62
  • 69

1 Answers1

0

You are mixing concepts: temp is a pointer, items[i] is an ITEM, items+i+1 is a pointer. So, if you want to use pointers, the good code must be:

// creating items
ITEMS **items = new ITEM*[set.pathc];
....
// for filling data
for (i = 0; i < set.pathc; i++)
{
    *(items + i) = new ITEM;    // new ITEM in pointer
    (*(items + i))->data = .....;
}

.....
// compare and switching data
if (compare(*(items + i), *(items + i + 1) .....)
{
    ITEM *temp = *(items + i);
    *(items + i) = *(items + i + 1);
    *(items + i + 1) = temp;
}

Of course, you can declare, as now:

ITEM *items = new ITEM[set.pathc];

but in this case, the switching code can't do with pointers because you are not storing pointers in your array, just ITEMS.

If there are no much switching situations in your problem, I suggest not using ITEM ** because dynamic allocation overhead.

Tio Pepe
  • 3,071
  • 1
  • 17
  • 22
  • I've already rewritten the code, but could you please tell me what did you mean by "dynamic allocation overhead" and why not to use "`ITEM * *`"? Now, I have it like this (but have problem with allocating big memory): `ITEM * * items; items = (ITEM * *) malloc( sizeof(ITEM* *) * set.pathc); for(i = 0; i < set.pathc; i++) { ITEM *new_item = (ITEM *) malloc(sizeof(ITEM)); *(items+i) = new_item; /* Sets item name and path*/ (*(items+i))->SetFullPath(); }` and Im sorting with memcpy (->temp, ->first, temp->second). But I guess its slow. – Buksy Dec 22 '11 at 11:42
  • Normally, dynamic allocation, using new / malloc, produce overhead than normal stack creation & copy operations. If you have not to much items you can try using stack & items copy operations in your container because you have not to much sort operations. But, if item count is so high, and the container is, normally, so much unsorted, a better performance is done by switching pointers – Tio Pepe Dec 22 '11 at 11:53