繁体   English   中英

C ++选择按结构数组排序

[英]C++ Selection Sort on Array of Structures

我正在阅读一本C ++书,但是我对其中一个挑战性问题有些困惑。 我正在学习有关指针的知识,在这个特殊的问题中,我需要对一个结构数组(使用指针)进行排序,并使用一个学生名的字符串和分数的两倍。 排序之后,结构的数据成员显然仍需要匹配(即,正确的名称仍需要与它们的分数保持一致)。

这就是我的问题所在。 到目前为止,我已经按照升序正确地排列了分数,但是名称全都混乱了。 我一直无法弄清楚为什么,部分原因是我仍在努力完全理解指针以及如何使用它们。 我可以正确地进行冒泡排序,将名称与得分保持一致,但不能进行选择排序。 任何帮助将不胜感激。

这是我用于选择排序的功能:

void selection_sort(Student *ptr, int size) // selection sort - having some problems
{
  int start,
    min_index,
    min_value;

  for (start = 0; start < (size - 1); start++) {
    min_index = start;
    min_value = (ptr+start)->score;
    for (int index = start+1; index < size; index++) {
      if ( (ptr+index)->score < min_value) {
    min_value = (ptr+index)->score;
    min_index = index;
      }
    }
    // the following line is where, i think, the problem is, but i haven't
    // been able to figure out the solution, despite trying numerous approaches
    *(ptr+min_index) = *(ptr+start);
    (ptr+start)->score = min_value;
  }
}

这就是我所拥有的。 我对排序算法也不是很满意,这对我来说还很新,所以我希望它不会被搞砸。 如果在这些领域有知识的任何人都可以指出正确的方向,那就太好了。

首先,我想给您一个提示:您可以使用ptr[min_index]而不是使用语法*(ptr+min_index)来达到相同的效果。 我相信这个版本更自然。

第二-您的问题。 您应该交换ptr[min_index]ptr[start]而不是仅将其中一个的值复制到另一个。 而不是:

*(ptr+min_index) = *(ptr+start);
(ptr+start)->score = min_value;

这样写:

Student temp = ptr[start];
ptr[min_index] = ptr[start];
ptr[start] = temp;

或者,如果您使用的是c ++,则只需使用swap函数:

std::swap(ptr[min_index], ptr[start]);

为什么要交换而不是当前正在做什么? 好吧,您应该保留ptr[min_index]中的所有字段,以便能够将它们分配给ptr [start]。

希望这可以帮助。

我认为您应该在标准库中使用memcpy函数...

还有一件事:

*(ptr+min_index) = *(ptr+start); 

这行似乎覆盖了数据,但没有按原样交换它们。

C ++的第一课:在C ++中,我们有运算符重载,因此如下所示:

 *(ptr+min_index) = *(ptr+start); 

如果您的Student类的成员属性中有任何指针,则可能具有含义。

并且您必须使用交换,而不仅仅是分配。

暂无
暂无

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

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