2012-03-03 75 views
0

我正在通过一本C++书籍,并且我对这个挑战问题有点困惑。我正在学习关于指针的知识,在这个特定的问题中,我需要用一串学生的名字和他们得分的两倍来排序结构数组(使用指针)。排序后,结构的数据成员仍然需要匹配,显然(即正确的名称仍然需要与他们的分数)。结构阵列上的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; 
    } 
} 

所以这是我的。对于排序算法我也不是很好,这对我来说都很新颖,所以我希望它不会被搞糟。如果在这些领域有经验的人可以指引我朝着正确的方向发展,那将会很棒。

+0

在C++中,不会将指针和大小作为参数传递给函数。而是使用标准容器(例如向量)并传递开始和结束迭代器。 – 2012-03-03 08:39:16

回答

4

首先,我想给你一个建议:不要使用语法*(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++简单地使用交换功能:

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

为什么你应该换什么,而不是你目前在做什么?那么,你应该保留ptr[min_index]中的所有字段,以便能够将它们分配给ptr [开始]。

希望这会有所帮助。

+0

啊......这就是值被覆盖的原因。谢了哥们。另外,你说得对,ptr [index]看起来好多了。 – nik 2012-03-03 08:52:54

1

我想你应该在标准库使用memcpy函数...

还有一件事:

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

此行似乎覆盖数据,但不会掉他们,因为他们应该是。

0

第一课在C++:在C++中,我们有操作符重载,所以像这样的行:

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

可以意味着,如果你的学生类在他的成员属性的任何指针。

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