当前位置:网站首页>How to maintain the length of a solid array and how to delete elements completely

How to maintain the length of a solid array and how to delete elements completely

2022-06-10 07:21:00 Zeke Luo

​ Problem description

Developing on the chain , There are often some businesses , For example, you need to store multiple addresses , And I can view these multiple addresses length, You can also specify a subscript to get a value , Or, , I need to delete the specified subscript , and length To update . Now my question is ,Array After deleting the value of the specified subscript , The value of this subscript becomes the default value , The business deletion we really want is not realized , So how to deal with it ?

Solution :

There are generally two ways to solve the above problems :

  1.   Delete , Then delete the element for Cycle to the last position , eject pop.
  2.   Replace , Replace the element to be deleted with the last element , Then the pop-up pop.

Two applicable scenarios :

  1. The first one is Consider array order , This does not disturb the order , But consumption gas
  2. The second kind Regardless of order , Length only , And save gas
 Code :
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.6;
contract ArrayRemoveByShifting {
uint[] public arr;

    function remove(uint _index) public {
        require(_index < arr.length, "index out of bound");
  
        for (uint i = _index; i < arr.length - 1; i++) {
            arr[i] = arr[i + 1];
        }
        arr.pop();
    }

    function test() external {
        arr = [1, 2, 3, 4, 5];
        remove(2);
        // [1, 2, 4, 5]
    }
/**----------------------- The above is the first way ---------------------------------**/

    function remove2(uint index) public {
        // Move the last element into the place to delete
        arr[index] = arr[arr.length - 1];
        // Remove the last element
        arr.pop();
    }

    function test() public {
        arr = [1, 2, 3, 4];
        remove2(1);
        // [1, 4, 3]
    }
/**----------------------- The above is the second way ---------------------------------**/

}

The above solutions can choose the best one according to their own business .

原网站

版权声明
本文为[Zeke Luo]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/161/202206100715161205.html