简体   繁体   中英

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.

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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