简体   繁体   English

如何对结构数组进行排序,这些结构具有指向同一数组的指针

[英]How to sort an array of structures, with these structures having pointers to the same array

I have an array of structures (vertex), each structure has a name, a color, an amount of neighbors, and an array of pointers (neighbors), all pointers reference a vertex in the main array of structures. 我有一个结构数组(顶点),每个结构都有一个名称,颜色,一定数量的邻居和一个指针数组(邻居),所有指针都引用结构主数组中的一个顶点。 I want to make some reorders based on name, color, etc, and the problem is this, whenever I do a reorder on the main array of structures, each array of neighbors loses the real address of the neighbors (because of the switching of the positions). 我想根据名称,颜色等进行一些重新排序,问题是,每当我对结构的主数组进行重新排序时,每个邻居数组都会丢失邻居的真实地址(因为切换了职位)。

I HAVE TO use qsort() , and I can't change the data structures. 必须使用 qsort()我不能改变的数据结构。

Here's the whole data structure: 这是整个数据结构:

struct VerticeSt {
    int vertice;
    int color;
    int cantVecinos;
    struct VerticeSt* (*vecinos)[];
};

If I understand correctly, the question is: 如果我理解正确,那么问题是:

How do I keep 2 data structures synchronized, if I sort one of them? 如果对其中一种排序,如何保持2种数据结构同步?

The current status is: 当前状态为:

sort()
{
    ...
    swap(a,b);
    ...
}

which of course does not touch the second data structure, therefore leading to loss of synchronization. 哪个当然不涉及第二个数据结构,因此导致失去同步。

I would use the following algorithm to keep them in sync: 我将使用以下算法使它们保持同步:

sort()
{
    ...
    swap(*pa, *pb);
    swap( pa,  pb);
    ...
}

The difference between the two is to add another line of code to handle the second data structure. 两者之间的区别是添加了另一行代码来处理第二个数据结构。

Think twice before moving a structure that is referenced from other nodes. 在移动从其他节点引用的结构之前,请三思。 As you sort the array of vertex, all the faces and the edges that point to them have to be actualised to point to the new place you have moved it. 在对顶点数组进行排序时,必须将所有指向它们的面和边都实现为指向已移动的新位置。 Or you'll lose all your data structure. 否则您将丢失所有数据结构。 For this reason is far more interesting to use an array of pointers and sort the array, instead of the whole structures. 因此,使用指针数组而不是整个结构对数组进行排序会更加有趣。 You can have three or four arrays of pointers showing the different orders, without breaking your mesh. 您可以使三个或四个指针数组显示不同的顺序,而不会破坏网格。 And copying a pointer is cheaper than copying a whole structure. 复制指针比复制整个结构便宜。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM