繁体   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