Menu
Coddy logo textTech

이터레이터 패턴

Coddy C 여정의 객체 지향 프로그래밍 섹션에 포함된 레슨. 61개 중 56번째.

Iterator 패턴은 기본 구조를 노출하지 않고 collection의 elements에 순차적으로 액세스할 수 있는 방법을 제공합니다. 사용자에게 array에 대한 direct 액세스를 제공하는 대신, 한 번에 하나의 element씩 data를 단계적으로 처리하는 방법을 아는 객체를 제공합니다.

iterator에는 일반적으로 두 가지 정보가 필요합니다: collection에 대한 참조와 current position입니다. C에서는 이 상태를 저장할 struct를 생성합니다.

typedef struct {
    int* data;      // 배열에 대한 포인터
    int size;       // 요소의 총 개수
    int current;    // 현재 위치
} IntIterator;

iterator는 두 가지 핵심 functions를 노출합니다. has_next()는 읽을 more elements가 있는지 checks하고, next()는 current element를 반환하며 position을 advances합니다.

int has_next(IntIterator* it) {
    return it->current < it->size;
}

int next(IntIterator* it) {
    return it->data[it->current++];
}

iterator를 사용하면 깔끔해 보이고 array 세부 정보가 숨겨집니다.

IntIterator it = create_iterator(numbers, 5);
while (has_next(&it)) {
    printf("%d\n", next(&it));
}

호출자는 numbers가 array인지 또는 indexing이 어떻게 작동하는지 전혀 알 필요가 없습니다. 이러한 추상화 덕분에 나중에 기본 데이터 구조를 array에서 연결 리스트로 변경하더라도 iterator를 사용하는 코드를 변경하지 않아도 되므로 쉽게 변경할 수 있습니다.

challenge icon

챌린지

쉬움

NumberList iterator를 만들어 봅시다. underlying array 구조를 노출하지 않고 integer의 collection을 순회할 수 있게 해 주는 깔끔한 abstraction입니다.

코드를 세 개의 파일로 구성합니다.

  • iterator.h: integer array에 대한 pointer, collection의 전체 크기, current position을 저장하는 IntIterator struct를 Define합니다. 세 가지 functions를 Declare합니다. create_iterator (array pointer와 size를 받아 initialized iterator를 반환), has_next (more elements가 남아 있는지 checks), next (current element를 반환하고 position을 advances). include guards도 잊지 마세요!
  • iterator.c: iterator functions를 Implement합니다. create_iterator function은 current position이 0으로 설정된 IntIterator를 value로 반환해야 합니다. has_next function은 읽을 more elements가 있으면 1을, otherwise 0을 반환합니다. next function은 current position의 element를 반환한 다음 position을 increments합니다.
  • main.c: elements의 number를 읽은 다음, 각 integer value를 array로 읽어 들입니다. 이 array에 대한 iterator를 Create한 다음, has_nextnext를 사용하는 while loop으로 순회하며 각 element를 자체 line에 print합니다.

프로그램은 다음을 입력으로 받습니다.

  1. array의 elements 수
  2. 각 line에 하나씩 주어지는 integer value

iterator pattern을 사용하여 모든 elements를 print하세요. 순회 loop에서 direct array indexing을 사용하지 마세요!

inputs가 4, 그다음 10, 20, 30, 40일 때의 Example output:

10
20
30
40

inputs가 3, 그다음 -5, 0, 100일 때의 Example output:

-5
0
100

inputs가 1, 그다음 42일 때의 Example output:

42

iterator는 data가 어떻게 저장되는지 숨깁니다. main loop는 array indices나 memory layout에 대해 아무것도 알 필요 없이 단순히 "is there more?"와 "give me the next one"을 요청합니다.

직접 해보기

#include <stdio.h>
#include "iterator.h"

int main() {
    int n;
    scanf("%d", &n);
    
    int arr[n];
    
    // TODO: n개의 정수 값을 배열에 읽기
    for (int i = 0; i < n; i++) {
        scanf("%d", &arr[i]);
    }
    
    // TODO: 배열에 대한 이터레이터 생성
    
    // TODO: has_next와 next를 사용하는 while 루프로 순회
    // 그리고 각 요소를 한 줄에 하나씩 출력
    // 순회 루프에서 직접 배열 인덱싱을 사용하지 마세요!
    
    return 0;
}
quiz icon실력 점검

이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.

객체 지향 프로그래밍의 모든 레슨

직접 연습해 보세요: 온라인 C 컴파일러