0

重複の可能性:
構造体を使用した 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();
}

array の送信方法と並べ替え方法を知りたいですb。また、デストラクタと、それらをコードのどこに配置できるかについて質問するつもりでした。

4

2 に答える 2

1

特定の要素で配列を並べ替える場合は、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);
    }
}

これは、配列のソートに使用される一般的なクイックソート関数です。データを表す適切な変数を置き換えるだけです。たとえば、T * 要素は Fish * stuff になり、T t = Elements[first] は double price = stuff[first] になります。

于 2012-11-01T13:38:10.397 に答える
0

あなたがソートしているときに魚を交換するには、これを書くべきです

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

魚の価格に基づいて選別していますが、選別する必要があるのは魚全体です。

あなたの他の質問では、このコードにデストラクタは必要ありません。fish クラスは「クリーンアップ」を行う必要がないため、デストラクタは必要ありません。

于 2012-11-01T12:32:02.093 に答える