簡體   English   中英

使用選擇排序對對象數組進行排序 c++

[英]Using a selection sort to sort an array of objects c++

目前,我編寫了一個基本的選擇排序,我需要讓它根據 class 成員對對象數組進行排序 - 如果對守門員 [MAX_GOALIES].getWins() 進行排序,則 getWins() 中的整數需要按降序排列. 這是我到目前為止對 function 進行排序的內容:

void sortWins(int array[], int size)
{
    int maxIndex, maxValue;
    
    for (int start=0;start<(size -    1);start++)
    {
        maxIndex = start;
        maxValue = array[start];
        for (int index = start + 1; index < size; index ++)
        {
            if (array[index].getWins() > maxValue.getWins())
            {
                maxValue = array[index];
                maxIndex = index;
            }
        }
        swap(array[maxIndex], array[start]);
    }
}

我如何確保排序 function 正在排序 class 成員 getWins()?

您可以使用std::sort function,指定您想要的排序標准。 一個可能的例子是:

std::sort(objectsVector.being(), objectsVector.end(), [](object a, object b) -> bool {
   return a.getWins() > b.getWins();
});

這樣,在 objectsVector 中,您將成為對象列表,按降序排列。

如果要使用實現選擇排序的自定義 function,則必須將對象數組而不是整數傳遞給此 function。 然后在您的 function 中,您將對 getWins() 返回的值進行比較

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM