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

C++ STL list 컨테이너로 정렬 기능 구현하기

이 C++ 프로그램에서는 STL(표준 템플릿 라이브러리)의 list 컨테이너를 활용하여 요소를 삽입하고 정렬된 상태로 출력하는 메뉴 기반 프로그램을 구현합니다. 사용자가 원하는 값을 계속 추가할 수 있고, 언제든지 현재까지 입력된 값들을 오름차순으로 정렬하여 확인할 수 있는 구조입니다.

사용되는 주요 함수 및 설명

여기서 사용된 함수들:
    l.push_back() = 리스트의 맨 뒤에 새로운 요소를 추가합니다.
    l.sort()      = 리스트의 모든 요소를 오름차순으로 정렬합니다.
    ※ 위에서 l은 list 객체를 의미합니다.

예제 코드

#include <iostream>
#include <list>
#include <string>
#include <cstdlib>
using namespace std;
int main() {
    list<int> l;
    list<int>::iterator it;
    int c, i;
    while (1) {
        cout<<"1.Insert Element to the list"<<endl;
        cout<<"2.Display the List"<<endl;
        cout<<"3.Exit"<<endl;
        cout<<"Enter your Choice: ";
        cin>>c;
        switch(c) {
            case 1:
                cout<<"Enter value to be inserted";
                cin>>i;
                l.push_back(i);
            break;
            case 2:
                l.sort();
                cout<<"Elements of the List: ";
                for (it = l.begin(); it != l.end(); it++)
                    cout<<*it<<" ";
                cout<<endl;
            break;
            case 3:
                exit(1);
            break;
            default:
                cout<<"Wrong Choice"<<endl;
        }
    }
    return 0;
}

프로그램 동작 방식

프로그램은 무한 루프(while(1)) 안에서 사용자의 선택을 반복해서 입력받습니다. 각 메뉴의 역할은 다음과 같습니다.

- 메뉴 1 (요소 삽입): 사용자로부터 정수를 입력받아 push_back()으로 리스트 뒤쪽에 추가합니다.
- 메뉴 2 (리스트 출력): sort() 함수를 호출해 리스트를 오름차순으로 정렬한 뒤, 이터레이터(iterator)를 이용해 처음부터 끝까지 순회하며 모든 요소를 출력합니다.
- 메뉴 3 (종료): exit(1)을 호출하여 프로그램을 종료합니다.
- 그 외의 입력: "잘못된 선택"이라는 안내 메시지를 출력하고 다시 메뉴로 돌아갑니다.

실행 결과

1.Insert Element to the list
2.Display the List
3.Exit

Enter your Choice: 1
Enter value to be inserted7
1.Insert Element to the list
2.Display the List
3.Exit

Enter your Choice: 1
Enter value to be inserted10
1.Insert Element to the list
2.Display the List
3.Exit

Enter your Choice: 1
Enter value to be inserted6
1.Insert Element to the list
2.Display the List
3.Exit

Enter your Choice: 1
Enter value to be inserted4
1.Insert Element to the list
2.Display the List
3.Exit

Enter your Choice: 2
Elements of the List: 4 6 7 10
1.Insert Element to the list
2.Display the List
3.Exit
Enter your Choice: 3

Exit code: 1

실행 결과를 보면 7, 10, 6, 4 순서로 입력했음에도 불구하고, 메뉴 2를 통해 출력할 때 sort() 함수 덕분에 4 6 7 10으로 오름차순 정렬되어 표시되는 것을 확인할 수 있습니다. 이처럼 STL의 list 컨테이너는 내장된 정렬 기능을 제공하므로, 별도의 정렬 알고리즘을 직접 구현하지 않고도 손쉽게 정렬된 데이터를 관리할 수 있습니다.