Solidity中按voteCount排序结构体数组的实现求助
Solidity结构体数组按voteCount排序实现
实现思路
在Solidity中,view函数无法修改链上存储数组的顺序,因此我们需要先将存储中的候选人数组复制到内存数组,再对内存数组使用冒泡排序(适合候选人数量不多的投票场景,实现简单)按voteCount字段排序,最后返回排序后的数组。
完整实现代码
// 修正语法错误并实现排序逻辑 function sortCandidate() public view returns(Candidate[] memory){ // 1. 复制存储数组到内存数组 Candidate[] memory sortedCandidates = new Candidate[](registeredCandidates.length); for (uint i = 0; i < registeredCandidates.length; i++) { sortedCandidates[i] = registeredCandidates[i]; } // 2. 冒泡排序:按voteCount降序排列(得票从高到低) uint length = sortedCandidates.length; for (uint i = 0; i < length; i++) { for (uint j = 0; j < length - i - 1; j++) { // 前一个候选人得票少于后一个时,交换位置 if (sortedCandidates[j].voteCount < sortedCandidates[j+1].voteCount) { Candidate memory temp = sortedCandidates[j]; sortedCandidates[j] = sortedCandidates[j+1]; sortedCandidates[j+1] = temp; } } } return sortedCandidates; }
补充说明
- 若需要升序排列(得票从低到高),只需将判断条件改为
sortedCandidates[j].voteCount > sortedCandidates[j+1].voteCount。 - 冒泡排序时间复杂度为O(n²),如果候选人规模极大,可替换为快速排序等高效算法,但投票场景下冒泡排序的简单性足够适用。
- 该函数为
view类型,仅读取链上数据,不会产生写入交易的Gas消耗。
内容的提问来源于stack exchange,提问作者LSKs
相关产品推荐
相关产品推荐

