首页 > 解决方案 > 如何通过 Solidity 中的多个键对 Struct 数组进行排序?

问题描述

我有这样的结构

struct OfferBid {
            string id_user;
            uint qty_energy;
            uint typ;
            uint price_energy;
            uint status;
            uint t_submission;
            uint ts_delivery;
            uint number;
            uint quality_energy;
       }

我有一个这个结构的数组:

OfferBid[] tempOffers;

我发现了如何排序tempOffersprice_energy我使用这个函数从字段中创建一个单元数组price

function quickSortOffersBidsPrice(Lb.Lib.OfferBid[] memory arr, bool ascending) public view returns(Lb.Lib.OfferBid[] memory) {
        if(arr.length == 0) return arr;
        uint[] memory prices = lib.arr_of_prices_offerbids(arr);
        Lb.Lib.OfferBid[] memory sorted = get_indices_and_sort(prices,arr,ascending);
        return sorted;
    }

它调用了这些其他函数:在这里,我使用结构数组的索引创建了一个单元数组。

function get_indices_and_sort(uint[] memory values, Lb.Lib.OfferBid[] memory offers_bids, bool ascending) private pure returns(Lb.Lib.OfferBid[] memory) {
        uint[] memory indices = new uint[](values.length);
        for (uint z = 0; z < indices.length; z++) {
            indices[z] = z;
        }
        Sorting.quickSort_indices(values, 0, int(values.length-1), indices);
        if(!ascending){
            indices = reverseArray(indices);
        }
        Lb.Lib.OfferBid[] memory sorted = new Lb.Lib.OfferBid[](values.length);
        for (uint z = 0; z < indices.length; z++) {
            sorted[z] = offers_bids[indices[z]];
        }
        return sorted;
    }

我对价格数组进行排序,然后同时对指数进行排序。然后我可以对结构的原始数组进行排序

function quickSort_indices(uint[] memory arr, int left, int right, uint[] memory indices) public pure {
        int i = left;
        int j = right;
        if (i == j) return;

        uint pivot = arr[uint(left + (right - left) / 2)];

        while (i <= j) {
            while (arr[uint(i)] < pivot) i++;
            while (pivot < arr[uint(j)]) j--;
            if (i <= j) {
                (arr[uint(i)], arr[uint(j)]) = (arr[uint(j)], arr[uint(i)]);
                (indices[uint(i)], indices[uint(j)]) = (indices[uint(j)], indices[uint(i)]);
                i++;
                j--;
            }
        }
        if (left < j)
            quickSort_indices(arr, left, j, indices);
        if (i < right)
            quickSort_indices(arr, i, right, indices);
    }

我怎样才能先排序price_energy,如果相同price_energy,排序qty_energy

标签: arrayssortingethereumsolidity

解决方案


由于 int256 具有足够大的维度,您可以使用复合键进行排序:key= (price_energy<<128) | qty_energy

此外,不是在数组完全形成之后而是在添加元素时递增地对数组进行排序可能更有效。


推荐阅读