qsort后识别项目/类指针
第一个问题所以请原谅我的天真。
我正在深入研究 C++ 的三角测量库,它在运行三角测量方法之前对结构指针数组进行排序。我试图在整个应用程序中跟踪一个特定的结构指针(XYZ),该指针根据鼠标位置进行更新。问题是,每当应用 qsort 方法时,此指针就会发生变化。如何识别或跟踪这个 struct XYZ 指针?
这是结构 &排序...
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);
}
带有鼠标指针引用的 XYZ 结构数组(此处有 2 个用于测试)...
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];
排序和更新鼠标方法。
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
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 position. 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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您有几个选择:
bsearch
查找它。您可以通过使用bsearch
来查找正确的X
坐标,然后对标记进行(较短的)线性搜索,从而将这些组合起来。XYZ
结构数组进行排序,而是在该数组中创建索引或指针的并行列表,并对XYZ *
或int
引用进行排序。您的mousePointer
引用仍然有效。You have a couple of options:
bsearch
for it in the sorted array. You could combine those by usingbsearch
to find the rightX
coordinate followed by a (shorter) linear search for the marker.XYZ
structures, create a parallel list of indexes or pointers into that array and sort theXYZ *
orint
references instead. YourmousePointer
reference will remain valid.qsort() 的第三个参数不应该是 size(XYZ*) 吗?您正在对指针进行排序,而不是对所指向的对象进行排序。
Shouldn't the third arg to qsort() be size(XYZ*)? You're sorting the pointers and not the objects being pointed to.