[英]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.