언어/C++

8일차)C++ 문법 단기간에 끝내기!! 기초 문법편<<STL

CodeMuscle 2024. 12. 6. 17:38
반응형

 

 

안녕하세요. CodeMuscle 입니다.

 

 

C++ STL 가이드: 컨테이너, 알고리즘, 이터레이터, 파일 입출력

C++의 **STL (Standard Template Library)**은 프로그래머가 자주 사용하는 자료구조와 알고리즘을 편리하게 사용할 수 있도록 도와주는 라이브러리입니다. 


1. 컨테이너 클래스

컨테이너는 데이터를 저장하고 관리하는 데 사용됩니다. STL에는 다양한 컨테이너가 포함되어 있어 데이터를 효율적으로 처리할 수 있습니다.

1.1 벡터 (std::vector)

std::vector는 크기가 가변적인 동적 배열입니다. 요소를 추가하거나 삭제할 수 있으며, 크기를 자동으로 조절합니다.

#include <vector>
#include <iostream>

int main() {
    std::vector<int> numbers = {1, 2, 3, 4, 5};
    numbers.push_back(6); // 새로운 요소 추가
    
    for (int num : numbers) {
        std::cout << num << " "; // 출력: 1 2 3 4 5 6
    }
    return 0;
}

 

1.2 리스트 (std::list)

std::list는 이중 연결 리스트로, 요소의 삽입과 삭제가 빠릅니다. 중간에 요소를 삽입하거나 삭제하는 데 유리합니다.

#include <list>
#include <iostream>

int main() {
    std::list<int> numbers = {10, 20, 30};
    numbers.push_front(5); // 앞에 요소 추가
    numbers.push_back(40); // 뒤에 요소 추가

    for (int num : numbers) {
        std::cout << num << " "; // 출력: 5 10 20 30 40
    }
    return 0;
}

 

1.3 맵 (std::map)

std::map은 키-값 쌍을 저장하며, 키를 기준으로 자동 정렬됩니다. 데이터를 키로 빠르게 검색할 수 있습니다.

#include <map>
#include <iostream>

int main() {
    std::map<std::string, int> scores;
    scores["Alice"] = 90;
    scores["Bob"] = 85;

    for (const auto& pair : scores) {
        std::cout << pair.first << ": " << pair.second << std::endl;
    }
    return 0;
}

 

1.4 셋 (std::set)

std::set은 중복되지 않는 고유한 값을 저장하며, 자동으로 정렬합니다.

#include <set>
#include <iostream>

int main() {
    std::set<int> uniqueNumbers = {1, 2, 2, 3, 4};
    uniqueNumbers.insert(5);

    for (int num : uniqueNumbers) {
        std::cout << num << " "; // 출력: 1 2 3 4 5
    }
    return 0;
}

 

1.5 배열, 큐, 스택

  • 배열 (std::array): 고정된 크기의 배열입니다.
  • 큐 (std::queue): FIFO (First-In-First-Out) 구조입니다.
  • 스택 (std::stack): LIFO (Last-In-First-Out) 구조입니다.
#include <array>
#include <queue>
#include <stack>
#include <iostream>

int main() {
    // 배열
    std::array<int, 3> arr = {1, 2, 3};
    for (int num : arr) {
        std::cout << num << " ";  // 출력: 1 2 3
    }

    // 큐
    std::queue<int> q;
    q.push(10);
    q.push(20);
    std::cout << q.front() << std::endl;  // 출력: 10

    // 스택
    std::stack<int> s;
    s.push(5);
    s.push(15);
    std::cout << s.top() << std::endl;  // 출력: 15

    return 0;
}

2. 알고리즘

STL 알고리즘은 컨테이너의 데이터를 정렬, 검색, 변환하는 데 사용됩니다.

2.1 정렬

std::sort를 사용해 벡터의 요소를 정렬할 수 있습니다.

#include <algorithm>
#include <vector>
#include <iostream>

int main() {
    std::vector<int> numbers = {5, 3, 8, 1, 2};
    std::sort(numbers.begin(), numbers.end());

    for (int num : numbers) {
        std::cout << num << " "; // 출력: 1 2 3 5 8
    }
    return 0;
}

2.2 검색

std::find를 사용해 벡터 내에서 특정 값을 찾을 수 있습니다.

#include <algorithm>
#include <vector>
#include <iostream>

int main() {
    std::vector<int> numbers = {1, 3, 5, 7, 9};
    auto it = std::find(numbers.begin(), numbers.end(), 5);

    if (it != numbers.end()) {
        std::cout << "Found: " << *it << std::endl; // 출력: Found: 5
    }
    return 0;
}

3. 이터레이터

이터레이터는 컨테이너의 요소에 순차적으로 접근하기 위해 사용됩니다.

3.1 기본 사용법

#include <vector>
#include <iostream>

int main() {
    std::vector<int> numbers = {1, 2, 3, 4, 5};
    for (auto it = numbers.begin(); it != numbers.end(); ++it) {
        std::cout << *it << " "; // 출력: 1 2 3 4 5
    }
    return 0;
}

 

3.2 begin(), end(), next(), prev()

  • begin(), end(): 컨테이너의 시작과 끝을 나타내는 이터레이터입니다.
  • next(), prev(): 이터레이터를 한 칸씩 이동합니다.
#include <vector>
#include <iterator>
#include <iostream>

int main() {
    std::vector<int> numbers = {10, 20, 30};
    auto it = std::next(numbers.begin(), 1);
    std::cout << *it << std::endl;  // 출력: 20
    return 0;
}

4. 기타 유용한 클래스들

  • std::pair: 두 개의 값을 쌍으로 저장합니다.
#include <utility>
#include <iostream>

int main() {
    std::pair<int, std::string> p = {1, "One"};
    std::cout << p.first << ", " << p.second << std::endl; // 출력: 1, One
    return 0;
}
  • std::tuple: 여러 개의 값을 저장할 수 있습니다.
#include <tuple>
#include <iostream>

int main() {
    std::tuple<int, double, std::string> t = {1, 2.5, "Hello"};
    std::cout << std::get<2>(t) << std::endl; // 출력: Hello
    return 0;
}

5. 파일 입출력 (File I/O)

파일 입출력은 파일에서 데이터를 읽거나 쓰기 위해 사용됩니다.

 

5.1 파일 스트림 (ifstream, ofstream, fstream)

  • ifstream: 파일 읽기
  • ofstream: 파일 쓰기
  • fstream: 파일 읽기와 쓰기를 모두 지원
#include <fstream>
#include <iostream>

int main() {
    // 파일 쓰기
    std::ofstream outFile("example.txt");
    outFile << "Hello, file!";
    outFile.close();

    // 파일 읽기
    std::ifstream inFile("example.txt");
    std::string content;
    inFile >> content;
    std::cout << "Content: " << content << std::endl; // 출력: Hello
    inFile.close();
    return 0;
}

 

5.2 바이너리 파일 처리

바이너리 파일을 다룰 때는 std::ios::binary 모드를 사용하고, write()read() 함수를 이용해 데이터를 처리합니다.

#include <fstream>

int main() {
    // 바이너리 파일 쓰기
    std::ofstream outFile("data.bin", std::ios::binary);
    int num = 12345;
    outFile.write(reinterpret_cast<char*>(&num), sizeof(num));
    outFile.close();
    return 0;
}

마무리

이 글에서는 C++의 STL을 활용해 데이터를 효율적으로 관리하고 다양한 알고리즘을 적용하는 방법에 대해 알아보았습니다. 컨테이너, 알고리즘, 이터레이터를 잘 이해하고 사용하면 더 깔끔하고 효율적인 C++ 코드를 작성할 수 있습니다. 다양한 예제를 직접 실행해 보면서 이해를 깊게 해 보세요!

더 나아가 각 컨테이너와 알고리즘의 특성을 파악하고 상황에 맞게 선택하면, 훨씬 더 성능 좋은 프로그램을 만들 수 있습니다.

 

 

반응형