arrays - 如何通过 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;
我发现了如何排序tempOffers
。price_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
?
解决方案
由于 int256 具有足够大的维度,您可以使用复合键进行排序:key= (price_energy<<128) | qty_energy
此外,不是在数组完全形成之后而是在添加元素时递增地对数组进行排序可能更有效。
推荐阅读
- php - 在 WooCommerce 内容小部件中的产品标题之后显示 ACF 自定义字段
- sql - 加入 NM 关系表的 SQL 输出
- python - 合并具有不同列名和不同行数的多个数据框
- javascript - 无法读取 Redux 中未定义的属性“类型”
- python - 在 python 中检索词重或 TF_IDF
- javascript - 如何将天气信息从服务器发送到 html 文本区域框?
- discord.js - 在不同的文件中使用客户端
- java - Spring - 当使用带有 json 的 DELETE 时返回错误请求
- css - 基于 Markdown 粗体强调改变 tr 的 CSS 样式
- android - 通知在 Activity 中有效,但在 Service 中无效