c/c++语言开发共享交换结构数组中的元素

说我有这个结构:

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;iCntriSmallest包含要交换的记录的索引。 我的代码不起作用,但我该如何解决?

    你需要交换元素,而不是指针,

     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 % 3dn", 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()是标准的,你可以用它来排序任何东西。

      以上就是c/c++开发分享交换结构数组中的元素相关内容,想了解更多C/C++开发(异常处理)及C/C++游戏开发关注计算机技术网(www.ctvol.com)!)。

      本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。

      ctvol管理联系方式QQ:251552304

      本文章地址:https://www.ctvol.com/c-cdevelopment/549698.html

      (0)
      上一篇 2021年1月14日
      下一篇 2021年1月14日

      精彩推荐