开发者

identify item/class pointer after qsort

开发者 https://www.devze.com 2023-03-18 08:14 出处:网络
first question so please forgive my naiveness here. I\'m diving into a triangulation library for c++, which sorts an array of struct pointers before running it\'s triangulation method. I\'m trying to

first question so please forgive my naiveness here.

I'm diving into a triangulation library for c++, which sorts an array of struct pointers before running it's triangulation method. I'm trying to keep track of one particular struct pointer (XYZ) throughout my app, which updates according to the mouse posit开发者_Go百科ion. Problem is, whenever the qsort method is applied, this pointer changes. How do I identify or keep track of this struct XYZ pointer?

Here is the struct & sort...

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);
}

The array of XYZ structs (2 here for testing) with mouse pointer reference...

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


You have a couple of options:

  • You could search for your unique entry after sorting. If you add a marker member search linearly for the marker. If any entry with a matching X/Y coordinate is as good as any other you could bsearch for it in the sorted array. You could combine those by using bsearch to find the right X coordinate followed by a (shorter) linear search for the marker.
  • You can add a layer of indirection. Instead of sorting your array of XYZ structures, create a parallel list of indexes or pointers into that array and sort the XYZ * or int references instead. Your mousePointer reference will remain valid.


Shouldn't the third arg to qsort() be size(XYZ*)? You're sorting the pointers and not the objects being pointed to.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号