根据属性C 对对象进行排序

sort an array of objects based on property c++

本文关键字:排序 对象 属性      更新时间:2023-10-16

可能的重复:
C 与结构排序

#include <iostream>
using namespace std;
class fish{
private:
    int size;
    int price;
public:
    fish()
    {
        size=0;
        price=0;
    }
    void set_price(int x)
    {
        price=x;
    }
    void set_size(int g)
    {
        size=g;
    }
    int get_size()
    {
        return size;
    }
    int get_price()
    {
        return price;
    }
    void display()
    {
        cout<<" Fish price is "<<price<<" Fish size is "<<size<<endl;
    }
    void sort(fish h[5])
    {
        for (int o=0;o<=5;o++)
        {
            fish temp;
            temp.set_price(0);
            if (h[o].get_price()>h[o+1].get_price())
            {
                temp.get_price()=h[o].get_price();
                h[o].get_price()=h[o+1].get_price();
                h[o+1].get_price()=temp.get_price();
            }
        }
    }
};
void main()
{
    fish a;
    fish b[5];
    a.set_size(500);
    a.set_price(2);
    a.display();
    for (int i=0;i<=5;i++)
    {
        b[i].set_size(i*2);
        b[i].set_price(i*100);
    }
    for (i=0;i<=5;i++)
        b[i].display();
}

我想找出如何发送数组b并对其进行排序。我还要询问破坏者以及可以将它们放入我的代码中的地方。

在排序时要交换鱼,应该写这

fish tmp = h[o];
h[o] = h[o+1];
h[o+1] = tmp;

您是根据鱼价进行排序的,但是应该分类的是整个鱼。

在您的另一个问题上,此代码中不需要驱动器。您的鱼类课程不需要进行任何"清理",因此不需要破坏者。

如果您想通过给定元素对数组进行排序,那么STL容器应该很好,如果不是,我将使用此方法

template<class T>
void quickSort(T * elements, unsigned int first, unsigned int last)
{
    if(first < last)                        //make sure params are in bounds
    {
        T t = elements[first];              //t is PIVOT
        unsigned lastLow = first;           //create last low item
        unsigned i;                         //used for loop/swapping
        for(i = first + 1; i <= last; i++)  //run through entire bounds
            if(elements[i] < t)             //if elements is less than Low
            {
                          << " adding one onto lastLow...n";
                lastLow++;                  //move lastLow up one
                swap(elements,lastLow, i);  //swap lastlow and i
            }
        swap(elements,first, lastLow);      //swap first and lastlow
        if(lastLow != first)                //if lastlow is not first element
            quickSort(elements, first, lastLow - 1);
        if(lastLow != last)                 //if lastlow is not last element
            quickSort(elements, lastLow + 1, last);
    }
}

这是用于对数组进行排序的常见QuickSort函数。只需替换正确的变量以表示您的数据,例如t *元素变成鱼 *东西,t t =元素[第一个]变为双重价格= fitf [first]等。