简体   繁体   English

对象数组的选择排序

[英]selection sort for array of objects

Iam trying to make selection sort for array of objects considering i have Data class考虑到我有数据 class,我正在尝试对对象数组进行选择排序

I want to sort them depending on the id attribute of the object我想根据 object 的 id 属性对它们进行排序

class Data
{
public:
    string name;
    int id;
};

    }
int main()
{
    Data m[3];
    m[0].id = 5;
    m[1].id = 4;
    m[2].id = 8;
    selsort(m, 3);
    cout << m[0].id;
};

I cannot understand what is wrong nothing happens to the array?我不明白出了什么问题,阵列没有任何反应?

It seems there is a typo in the function declaration function 声明中似乎有错字

void selsort(media mry[], int n)
             ^^^^^

I think you mean我想你的意思是

void selsort( Data mry[], int n)
              ^^^^

This if statement这个 if 语句

if ((mry[min].id < mry[j].id) < 0)

does not make sense.没有意义。

You should write你应该写

if ( mry[min].id < mry[j].id )

Or if you want to sort in the ascending order then write the condition like或者,如果您想按升序排序,则将条件写为

if ( mry[j].id < mry[min].id )

Change:改变:

if ((mry[min].id < mry[j].id) < 0)

to:至:

if ((mry[min].id > mry[j].id) )

You are finding the minimum index, so you have to swap if you find an index with a value that is lesser than the current minimum.您正在寻找最小索引,因此如果您找到一个值小于当前最小值的索引,则必须进行交换。

A better way to accomplish this is to make your function take in another parameter called a comparator function which tells the function how to compare;实现此目的的更好方法是让您的 function 采用另一个称为比较器 function 的参数,它告诉 function 如何比较; that way you can reuse your function if you change to mind and what to sort it by another parameter.这样你就可以重复使用你的 function 如果你改变主意并通过另一个参数对其进行排序。

void selsort(Data mry[], int n, std::function<int(Data, Data)> cmp) // mry[] is the object array, n is the 
                                     // number of objects in the array
    {
        int pass, j, min;
        Data temp;
        for (pass = 0; pass <= n - 2; pass++)  // passes
        {
            min = pass;
            for (j = pass + 1; j < n; j++)  // in each pass
                if (cmp(mry[min], mry[j]) > 0)
                    min = j;
            temp = mry[min];
            mry[min] = mry[pass];
            mry[pass] = temp;
        }

    }

And you can define a compare by id function:您可以通过id function 定义比较:

int compare_by_id(Data d1, Data d2) 
{
    return d1.id - d2.id;
}

Call your function like this:像这样调用您的 function:

selsort(array, size, compare_by_id);

The best part is you can define your own function that can compare the elements as you want and that way your selsort() is versatile.最好的部分是您可以定义自己的 function 可以根据需要比较元素,这样您的selsort()是通用的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM