交换结构数组中的元素
说我有这个结构:
struct MyStruct { int iID; int iMyNumber; };
然后我定义了一个MyStructs数组:
struct MyStruct msTest[3];
我正在通过查看ID对类似于此的结构进行排序操作。 现在,一旦我发现应该交换哪些记录来对数组进行排序,我就必须进行实际的交换。 我试过这个:
if (iSmallest != iCntr) { stPTmp = &stXDB[iCntr]; &stXDB[iCntr] = &stXDB[iSmallest]; &stXDB[iSmallest] = &stPTmp; }
stPTmp定义为void *stPTmp;
和iCntr
和iSmallest
包含要交换的记录的索引。 我的代码不起作用,但我该如何解决?
你需要交换元素,而不是指针,
struct MyStruct stTmp; if (iSmallest != iCntr) { stTmp = stXDB[iCntr]; stXDB[iCntr] = stXDB[iSmallest]; stXDB[iSmallest] = stTmp; }
效率不是很高,但你的结构很小,所以它只比交换指针贵一点。
你可以让别人想一想,即使用qsort()
:
#include int compare_struct(const void *a, const void *b) { const struct MyStruct *sa = a, *sb = b; return (sa->iID < sb->iID) ? -1 : sa->iId > sb->iId; } qsort(msTest, sizeof msTest / sizeof *msTest, sizeof *msTest, compare_struct);
请注意,这完全消除了编写交换function的需要。 在幕后,这可能会更昂贵(可以使用malloc()
,几乎肯定使用memcpy()
),但它更容易编写,更容易维护。
John已经回答了你的问题,但是为了对你的struct
进行排序,你可以使用标准库qsort()
函数:
#include #include struct MyStruct { int iID; int iMyNumber; }; /* comparison function, should return < 0, > 0 or == 0 if a < b, a > b or a == b respectively. Used by qsort */ static int comp_mystruct(const void *a, const void *b); /* utility function to print an array of our struct */ static void print_mystruct(const void *start, size_t n); int main(void) { /* some data */ struct MyStruct data[] = { { 1, 10 }, { 5, 50 }, { 2, 20 }, { -3, 100 } }; size_t ndata = sizeof data / sizeof data[0]; /* before sorting */ print_mystruct(data, ndata); putchar('\n'); /* sort the array now */ qsort(data, ndata, sizeof data[0], comp_mystruct); /* after sorting */ print_mystruct(data, ndata); return 0; } static void print_mystruct(const void *start, size_t n) { size_t i; const struct MyStruct *s = start; for (i=0; i < n; ++i) { printf("% 3d % 3d\n", s[i].iID, s[i].iMyNumber); } } static int comp_mystruct(const void *a, const void *b) { const struct MyStruct *sa = a; const struct MyStruct *sb = b; if (sa->iID > sb->iID) { return 1; } else if (sa->iID < sb->iID) { return -1; } else { return 0; } }
该计划的输出是:
1 10 5 50 2 20 -3 100 -3 100 1 10 2 20 5 50
优点是qsort()
是标准的,你可以用它来排序任何东西。