Created
March 20, 2022 22:37
-
-
Save rzvl/04a86530f60d326c810c7c7f7b71ae3e to your computer and use it in GitHub Desktop.
Remove an element by replacing last
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// SPDX-License-Identifier: MIT | |
pragma solidity ^0.8.7; | |
contract ArrayReplaceLast { | |
uint[] public arr; | |
function remove(uint _index) public { | |
arr[_index] = arr[arr.length - 1]; | |
arr.pop(); | |
} | |
function test() external { | |
arr = [1, 2, 3, 4]; | |
remove(1); | |
assert(arr[0] == 1); | |
assert(arr[1] == 4); | |
assert(arr[2] == 3); | |
assert(arr.length == 3); | |
arr = [3]; | |
remove(0); | |
assert(arr.length == 0); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment