YeongHwa Jin
YeongHwa Jin

Reputation: 455

How can I sort the array of class?

I have made the class having 2d array (4 x 4) and maximum value in 2d array like below:

class B {
public:
    int shape[4][4] = { 0 };
    int maxh = 0;

    B() {};

    void record(int module[4][4]) {
        for (int i = 0; i < 4; i++) {
            for (int j = 0; j < 4; j++) {
                shape[i][j] = module[i][j];
                if (shape[i][j] > maxh) { maxh = shape[i][j]; }
            }
        }
    }
};

If there is a class 'B' array,

B b_arr = new B[30000];

how do I sort the class object array by the maximum value?

I have tried to sort array like below code, but I have a stack overflow error.

int partition(B arr[], int p, int r) {
    int i = p - 1;
    for (int j = p; j < r; j++) {
        int cri = arr[r].maxh;
        if (arr[j].maxh < cri) {
            i++;
            B tmp = arr[i];
            arr[i] = arr[j];
            arr[j] = tmp;
        }
    }
    B tmp = arr[i + 1];
    arr[i + 1] = arr[r];
    arr[r] = tmp;
    return i + 1;
}


void quickSort(B arr[], int p, int r) {

    if (p < r) {
        int q = partition(arr, p, r);
        quickSort(arr, p, q - 1);
        quickSort(arr, q + 1, r);
    }
}

Upvotes: 0

Views: 90

Answers (2)

Chih-Chen Kao
Chih-Chen Kao

Reputation: 89

You can define your comparator for std::sort():

See the prototype below:

template< class RandomIt, class Compare >
void sort( RandomIt first, RandomIt last, Compare comp );

For example you can do:

std::sort(
    /*std::begin(b_arr)*/b_arr,
    /*std::end(b_arr)*/b_arr+30000,
    [](const B& left, const B& right){
        return left.maxh < right.maxh;
    }
);

Note that std::begin() and std::end() do not work with pointers to dynamic arrays. In this case you must specify the range by adding the size. I recommend using std::vector or std::array instead.

Upvotes: 2

Adrian Mole
Adrian Mole

Reputation: 51825

You could use std::qsort, if you define a comparator function for the class objects:

int bArrCompare(const void* a, const void* b) {
    const B* pa = reinterpret_cast<const B*>(a);
    const B* pb = reinterpret_cast<const B*>(b);
    return (pb->maxh - pa->maxh);
}

int main()
{
    B* b_arr = new B[30000];
    //...
    std::qsort(b_arr, 30000, sizeof(B), bArrCompare);
    //...
    return 0;
}

Upvotes: 2

Related Questions