Define item / class pointer after qsort

first question please forgive my naivety here.

I dive into the C ++ triangulation library, which sorts an array of struct pointers before running this triangulation method. I am trying to track one specific structure pointer (XYZ) throughout the application, which updates according to the position of the mouse. The problem is that whenever the qsort method is applied, this pointer changes. How to identify or track this XYZ structure pointer?

Here is the structure and sorting ...

struct XYZ{ double x, y, z; }; int XYZCompare(const void *v1, const void *v2){ XYZ *p1, *p2; p1 = (XYZ*)v1; p2 = (XYZ*)v2; if(p1->x < p2->x) return(-1); else if(p1->x > p2->x) return(1); else return(0); } 

An array of XYZ structures (2 here for testing) with a link to the mouse pointer ...

 XYZ *allPointers = new XYZ[100]; allPointers[0].x = 100; allPointers[0].y = 200; allPointers[0].z = 0; allPointers[1].x = 50; allPointers[1].y = 80; allPointers[1].z = 0; XYZ *mousePointer = &allPointers[0]; 

Sort and update mouse methods.

 mousePointer->x = mouseX; mousePointer->y = mouseY; // If I don't qsort here the reference is fine, but I need to. qsort(allPointers, 2, sizeof(XYZ), XYZCompare); // triangulate, etc 
+4
source share
2 answers

You have several options:

  • After sorting, you can search for your unique record. If you add a marker item search linearly for the marker. If any record with the corresponding X / Y coordinate is as good as any other, you can bsearch it in a sorted array. You can combine them using bsearch to find the correct X coordinate, followed by a (shorter) linear marker search.
  • You can add a layer of indirection. Instead of sorting an array of XYZ structures, create a parallel list of indexes or pointers into this array and instead sort the XYZ * or int links. Your mousePointer link will remain valid.
+3
source

Should the third argument qsort () be the size of (XYZ *)? You are sorting pointers, not the objects that you point to.

-1
source

All Articles