Computer >> 컴퓨터 >  >> 프로그래밍 >> C++

C++ STL array 컨테이너로 배열 구현하기: 의사코드와 완전한 예제

C++의 STL(표준 템플릿 라이브러리)에는 고정 크기 배열을 다룰 수 있는 array 컨테이너가 포함되어 있습니다. 이 컨테이너는 일반 배열보다 안전하고 편리하며, 크기 확인, 요소 접근, 반복자 순회 등 다양한 멤버 함수를 제공합니다.

이 글에서는 STL의 array를 활용해 배열에 대한 여러 연산을 메뉴 형태로 수행하는 C++ 프로그램을 소개합니다.

배열 연산 개요 및 의사코드

프로그램은 사용자에게 메뉴를 보여주고, 선택한 번호에 따라 아래와 같은 연산을 수행합니다.

  • 배열의 크기 출력
  • 배열에 값 삽입
  • 배열의 첫 번째(front) 요소 출력
  • 배열의 마지막(back) 요소 출력
  • 배열의 모든 요소 출력
  • 프로그램 종료

위 동작을 의사코드로 표현하면 다음과 같습니다.

Begin
In main(),
    While TRUE do
        Prints some choices.
        Take input of choice.
        Start the switch case
            When case is 1
                Print the size of the array.
                Break
            When case is 2
                Insert the values in array.
                Break
            When case is 3
                Print the front element of array.
                Break
            When case is 4
                Print the back element of array.
                Break
            When case is 5
                Print all the elements of the array.
                Break
            When case is 6
                Exit.
            When case is default
                Print wrong input.
End.

C++ 전체 예제 코드

아래는 위 의사코드를 실제로 구현한 C++ 코드입니다. <array> 헤더를 포함시키고, 크기가 7인 정수형 배열을 선언한 뒤 각 메뉴에 맞는 연산을 처리합니다.

#include <iostream>
#include <array>
#include <cstdlib>
using namespace std;
int main() {
    array<int, 7> a; // 배열 선언
    array<int, 7>::iterator it; // 반복자(iterator) 선언
    int c, i; // 정수 변수 선언
    a.fill(0); // 배열을 0으로 초기화
    int cnt = 0;
    while (1) {
        cout<<"1.Size of the array"<<endl;
        cout<<"2.Insert Element into the Array"<<endl;
        cout<<"3.Front Element of the Array"<<endl;
        cout<<"4.Back Element of the Array"<<endl;
        cout<<"5.Display elements of the Array"<<endl;
        cout<<"6.Exit"<<endl;
        cout<<"Enter your Choice: ";
        cin>>c;
        switch(c) {
            case 1:
                cout<<"Size of the Array: "; // 배열의 크기 출력
                cout<<a.size()<<endl;
                break;
            case 2:
                cout<<"Enter value to be inserted: "; // 배열에 값 삽입
                cin>>i;
                a.at(cnt) = i;
                cnt++;
                break;
            case 3:
                cout<<"Front Element of the Array: "; // 첫 번째 요소 출력
                cout<<a.front()<<endl;
                break;
            case 4:
                cout<<"Back Element of the Array: "; // 마지막 요소 출력
                cout<<a.back()<<endl;
                break;
            case 5:
                for (it = a.begin(); it != a.end(); ++it ) // 모든 요소 출력
                    cout <<" "<< *it;
                cout<<endl;
                break;
            case 6:
                exit(1); // 프로그램 종료
                break;
            default:
                cout<<"Wrong Choice"<<endl; // 잘못된 입력 처리
        }
    }
    return 0;
}

실행 결과

프로그램을 실행하면 메뉴가 반복해서 표시되고, 사용자가 선택한 연산 결과가 출력됩니다. 아래는 값 7부터 1까지 순서대로 삽입한 후 각 기능을 테스트한 예시입니다.

1.Size of the array
2.Insert Element into the Array
3.Front Element of the Array
4.Back Element of the Array
5.Display elements of the Array
6.Exit
Enter your Choice: 1
Size of the Array: 7
...
Enter your Choice: 2
Enter value to be inserted: 7
...
Enter your Choice: 3
Front Element of the Array: 7
...
Enter your Choice: 4
Back Element of the Array: 1
...
Enter your Choice: 5
7 6 5 4 3 2 1
...
Enter your Choice: 6
exit status 1

주요 함수 설명

size()

배열에 저장된 요소의 총 개수를 반환합니다. array<int, 7>로 선언했으므로 항상 7이 출력됩니다.

at(index)

지정한 인덱스 위치의 요소에 접근합니다. 범위를 벗어나면 out_of_range 예외를 발생시키므로 일반적인 [] 연산자보다 안전합니다.

front() / back()

front()는 배열의 첫 번째 요소를, back()은 마지막 요소를 반환합니다.

begin() / end()

배열의 시작과 끝을 가리키는 반복자를 반환합니다. 이 두 반복자를 이용해 for 루프로 배열의 모든 요소를 순회할 수 있습니다.

fill(value)

배열의 모든 요소를 지정한 값으로 채웁니다. 위 예제에서는 초기화를 위해 0으로 채웠습니다.

마무리

STL의 array 컨테이너는 고정 크기 배열이 필요할 때 유용하며, 크기 정보와 함께 다양한 편의 함수를 제공해 일반 배열보다 안전하게 사용할 수 있습니다. 위 예제를 응용하면 삽입, 삭제, 탐색 등 더 복잡한 배열 연산도 손쉽게 구현할 수 있습니다.