상세 컨텐츠

본문 제목

Solidity - Array

Programming Language/Solidity

by Yongari 2022. 12. 25. 09:33

본문

 

 

Array can have a compile-time fixed size or a dynamic size.

배열은 컴파일 시간이 고정적인 크기 또는 동적인 크기를 가질 수 있습니다.

즉 컴파일 타임에 배열 길이를 정하는 고정배열과 배열을 동적으로 할당하는 동적배열이 있습니다. 

 

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.13;

contract Array {
    // Several ways to initialize an array
    // 배열을 초기화하는 여러 가지 방법
    uint[] public arr;
    uint[] public arr2 = [1, 2, 3];
    // Fixed sized array, all elements initialize to 0
    // 고정된 크기의 배열(어레이), 모든 요소가 0으로 초기화됨
    uint[10] public myFixedSizeArr;

    function get(uint i) public view returns (uint) {
        return arr[i];
    }

    // Solidity can return the entire array.
 	// 솔리디티는 전체 배열을 반환할 수 있습니다. 
    // But this function should be avoided for
    // 그러나 이 함수는 다음에 대해 피해야한다.
    // arrays that can grow indefinitely in length.
    // 무한으로 확장이 가능한 배열


function getArr() public view returns (uint[] memory) {
        return arr;
    }

    function push(uint i) public {
        // Append to array
        // 배열에 추가하기
        // This will increase the array length by 1.
        // 이렇게 할 경우 배열의 크기는 1 증가합니다.
        arr.push(i);
    }

    function pop() public {
        // Remove last element from array
        // 배열의 마지막 요소를 제거합니다.
        // This will decrease the array length by 1
        // 배열의 길이는 1 감소합니다. 
        arr.pop();
    }

    function getLength() public view returns (uint) {
        return arr.length;
    }

    function remove(uint index) public {
        // Delete does not change the array length.
        // 삭제해도 배열 길이는 변경되지 않습니다.
        // It resets the value at index to it's default value,
        // 인덱스의 값을 기본값으로 재설정합니다.
        // in this case 0
        // 이 경우 0
        delete arr[index];
    }

    function examples() external {
        // create array in memory, only fixed size can be created
        // 메모리에 배열 생성, 고정 크기만 생성할 수 있음
        uint[] memory a = new uint[](5);
    }
}

 

 

 

 

Examples of removing array element

배열 요소 제거 예제

 

Remove array element by shifting elements from right to left
요소를 오른쪽에서 왼쪽으로 이동하여 배열 요소 제거

 

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.13;

contract ArrayRemoveByShifting {
    // [1, 2, 3] -- remove(1) --> [1, 3, 3] --> [1, 3]
    // [1, 2, 3, 4, 5, 6] -- remove(2) --> [1, 2, 4, 5, 6, 6] --> [1, 2, 4, 5, 6]
    // [1, 2, 3, 4, 5, 6] -- remove(0) --> [2, 3, 4, 5, 6, 6] --> [2, 3, 4, 5, 6]
    // [1] -- remove(0) --> [1] --> []

    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]
        assert(arr[0] == 1);
        assert(arr[1] == 2);
        assert(arr[2] == 4);
        assert(arr[3] == 5);
        assert(arr.length == 4);

        arr = [1];
        remove(0);
        // []
        assert(arr.length == 0);
    }
}

 

Remove array element by copying last element into to the place to remove

마지막 요소를 제거할 위치에 복사하여 배열 요소 제거

 

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.13;

contract ArrayReplaceFromEnd {
    uint[] public arr;

    // Deleting an element creates a gap in the array.
    // One trick to keep the array compact is to
    // move the last element into the place to delete.
    // 요소를 삭제하면 배열에 공백이 생성됩니다.
    // 어레이를 콤팩트하게 유지하는 한 가지 방법은
    // 마지막 요소를 삭제할 위치로 이동합니다.
    function remove(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];

        remove(1);
        // [1, 4, 3]
        assert(arr.length == 3);
        assert(arr[0] == 1);
        assert(arr[1] == 4);
        assert(arr[2] == 3);

        remove(2);
        // [1, 4]
        assert(arr.length == 2);
        assert(arr[0] == 1);
        assert(arr[1] == 4);
    }
}

 

 

Remix IDE 링크 : 
1번 코드링크 : Click

2번 코드링크 : Click
3번 코드링크 : Click

compile-time 뜻 : 링크

출처 : https://solidity-by-example.org/array/ 

 

Solidity by Example

 

solidity-by-example.org

 

'Programming Language > Solidity' 카테고리의 다른 글

Solidity - Structs  (0) 2022.12.25
Solidity - Enum  (0) 2022.12.25
Solidity - Mapping  (0) 2022.12.23
Solidity - For and While Loop  (0) 2022.12.23
Solidity - If / Else  (0) 2022.12.23

관련글 더보기