我正在通过一本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;
}
}
所以这是我的。对于排序算法我也不是很好,这对我来说都很新颖,所以我希望它不会被搞糟。如果在这些领域有经验的人可以指引我朝着正确的方向发展,那将会很棒。
在C++中,不会将指针和大小作为参数传递给函数。而是使用标准容器(例如向量)并传递开始和结束迭代器。 – 2012-03-03 08:39:16