Solidity0.8.0-删除数组元素通过替换

// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.7;

//remove array element by shifting elements to left
//[1,2,3,4,5,6] -- remove(2) --> [1,2,3,4,5,6,6] --> [1,2,4,5,6]//数组可以保留原有的顺序,缺点浪费gas,因为数组的长时还要执行循环向左移动

contract ArrayReplaceLast {
    uint[] public arr;
    //[1,2,3,4] --remove(1) -->[1,4,3] //将数组中最后一个元素去替换想要删除的元素,再将数组最后一个元素pop弹出,缺点是打乱顺序
    //[1,4,3] --remove(2) -->[1,4]
    function remove(uint _index) public {
        arr[_index] = arr[arr.length - 1];
        arr.pop();
    }

    function test() external {
        arr = [1,2,3,4];
        remove(1);
        //[1,4,3]
        assert(arr.lenght == 3);
        assert(arr[0] ==1);
        assert(arr[1] ==4);
        assert(arr[2] ==3);
    }
}

 

posted @ 2022-07-28 23:37  ZaleSwfit  阅读(216)  评论(0)    收藏  举报