[TIL] 2025-12-16 | C++ STL, vector, map, sort(), find(), Iterator

2025. 12. 16. 20:18·내배캠Unreal_TIL/C++
게임 개발자를 위한 C++ 문법 2-3

열공합시다!

1. WHY

STL (표준 템플릿 라이브러리)를 활용한 다양한 자료구조와 알고리즘 사용

- 컨테이너, 알고리즘, 반복자(Iterator)

2. WHAT

아래 모든 코드는 std:: 생략되어 있음

 

컨테이너: 데이터를 담는 자료구조

 

- 벡터

배열과 유사한 컨테이너, 인덱스 접근, 중간 삽입 삭제 비효율적

#include <vector>

// 1. 기본 생성 및 초기화 없이 선언
vector<int> vec1;

// 2. 특정 크기와 초기값으로 벡터 선언
vector<int> vec2(5, 10); // 크기 5, 모든 원소가 10으로 초기화

// 3. 리스트 초기화로 벡터 선언
vector<int> vec3 = {1, 2, 3, 4, 5};

// 4. 다른 벡터를 기반으로 복사 초기화
vector<int> vec4(vec3); // vec3의 복사본 생성
//vector<int> vec4 = vec3 하면 대입이 됨

// 5. 2차원 벡터 초기화
vector<vector<int>> vec2D(3, vector<int>(4, 7)); // 3x4 행렬, 모든 원소가 7로 초기화

 

  • 벡터 동작
vector<int> vec;
vec.push_back(10); // 맨 끝 원소 추가
vec.pop_back(); // 맨 끝 원소 제거 // 값을 리턴하진 않음!
vec.size() // 크기 값 리턴
vec.erase(vec.begin() + 1); // 두 번째 요소 제거 (index 1) // 이터레이터 위치 또는 구간

// 벡터 요소 출력
for (int num : vec) {
    cout << num << " ";
}

 

- 맵: {key:value}

#include <map>

// 선언
map<string, string> map1;

// 요소 추가
map1["KR"] = "Korea";
map1["US"] = "United States";
map1["JP"] = "Japan";

// 맵 요소 출력
for (const auto& pair : map1) {
    cout << "Country Code: " << pair.first << ", Country Name: " << pair.second << endl;
}

 

  • 맵 동작
// map은 key 순으로 오름차순 정렬

// insert() -> 값 추가
myMap.insert(make_pair(1, "Apple")); // pair 객체
myMap.insert({4, "Dog"}); // {}
myMap[7] = "Giraffe"; // []
 
// find() -> key 존재 확인 -> 존재O: 헤딩 키 이터레이터 반환 -> 존재X: map.end() 반환
auto it = myMap.find(key); // 키 찾기
if (it != myMap.end()) {
    cout << "Found! Key: " << it->first << ", Value: " << it->second << endl;
} else {
    cout << "Key " << key << " not found!" << endl;
}

myMap.size() // 크기 값 리턴
myMap.erase(key); // 특정 key 요소 삭제 // 존재하지 않는 키 삭제 시 0 반환
myMap.clear(); // 모든 요소 삭제

 

알고리즘 #include <algorithm>

 

- sort()

정렬 알고리즘, 사용자 정렬 함수 comp(a,b)

#include <iostream>
#include <algorithm> // sort 함수 포함
using namespace std;

bool compare(int a, int b) { // 정렬 기준
    return a > b; // 내림차순
}

int main() {
    int arr[] = {5, 2, 9, 1, 5, 6};
    int size = sizeof(arr) / sizeof(arr[0]); // 전체 바이트 / 요소 하나의 바이트 = 요소 개수

    // 내림차순 정렬
    sort(arr, arr + size, compare); // 배열 정렬
    //sort(vec.begin(), vec.end(), compare); // 벡터 정렬 예시

    // 결과 출력
    for (int i = 0; i < size; i++) {
        cout << arr[i] << " ";
    }
    return 0;
}

 

  • 클래스 타입 벡터 정렬 예시
#include <iostream>
#include <vector>
#include <algorithm> // sort 함수 포함
using namespace std;

class Person {
private:
    string name;
    int age;

public:
    // 생성자
    Person(string name, int age) : name(name), age(age) {}

    // Getter 함수
    string getName() const { return name; }
    int getAge() const { return age; }
};

// 다중 기준 정렬 함수 (나이 오름차순 → 이름 오름차순)
bool compareByAgeAndName(const Person& a, const Person& b) {
    if (a.getAge() == b.getAge()) {
        return a.getName() < b.getName(); // 이름 오름차순
    }
    return a.getAge() < b.getAge(); // 나이 오름차순
}

int main() {
    vector<Person> people = {
        Person("Alice", 30),
        Person("Bob", 25),
        Person("Charlie", 35),
        Person("Alice", 25)
    };

    // 나이 → 이름 순으로 정렬
    sort(people.begin(), people.end(), compareByAgeAndName);

    // 결과 출력
    for (const Person& person : people) {
        cout << person.getName() << " (" << person.getAge() << ")" << endl;
    }
    return 0;
}

 

- find()

컨테이너 내부에서 특정 원소를 찾아 이터레이터 반환

#include <iostream>
#include <vector>
#include <algorithm> // find 함수 포함
using namespace std;

int main() {
    vector<int> vec = {10, 20, 30, 40, 50};

    // 특정 값 30을 찾음
    auto it = find(vec.begin(), vec.end(), 30);

    if (it != vec.end()) {
        cout << "값 30이 벡터에서 발견됨, 위치: " << (it - vec.begin()) << endl;
    } else {
        cout << "값 30이 벡터에 없음" << endl;
    }
    return 0;
}
#include <iostream>
#include <algorithm> // find 함수 포함
#include <string>
using namespace std;

int main() {
    string str = "hello world";

    // 문자 'o' 찾기
    auto it = find(str.begin(), str.end(), 'o');

    if (it != str.end()) {
        cout << "문자 'o'가 문자열에서 발견됨, 위치: " << (it - str.begin()) << endl;
    } else {
        cout << "문자 'o'가 문자열에 없음" << endl;
    }
    return 0;
}

 

- 반복자

컨테이너 요소에 일관된 접근 방법 제공

 

  • 순방향 반복자: begin(), end()
  • 역방향 반복자: rbegin(), rend()
// 순방향 반복자를 사용해 짝수만 출력
for (auto it = numbers.begin(); it != numbers.end(); ++it) {
    if (*it % 2 == 0) {
        cout << *it << " ";
    }
}

// 순방향 반복자를 사용해 맵의 키-값 쌍 출력
for (auto it = scores.begin(); it != scores.end(); ++it) {
    cout << it->first << ": " << it->second << endl;
}

// auto = 초기화 값을 보고 변수의 타입을 자동으로 결정
#include <iterator>

// 두 이터레이터 사이의 거리(요소 개수)를 계산
distance(first, last);

 

더보기

파이썬 하다가 보니까 너무 헷갈림 !!! 이제 C++에 익숙해져야겠죠...🥲

 

“왜 <iterator>를 안 넣어도 컴파일이 되지?”

더보기

“간접 포함(Transitive include)” 때문

 

  • <algorithm> → 이터레이터 기반 알고리즘 → <iterator> 포함
  • <vector>, <string> → iterator 타입 사용 → 내부 포함

 

 

3. RESULT

  • 2-2 숙제
#include <iostream>

using namespace std;

//아래 3개의 함수를 하나의 템플릿 함수로 통합하세요

//int add(int a, int b) {
//    return a + b;
//}
//
//double add(double a, double b) {
//    return a + b;
//}
//
//std::string add(const std::string& a, const std::string& b) {
//    return a + b;
//}
template<typename T>
T add(T a, T b) {
    return a + b;
}

//아래 테스트 코드는 변역하지 마세요
int main() {
    // 정수 더하기
    cout << "3 + 5 = " << add(3, 5) << endl;

    // 실수 더하기
    cout << "2.5 + 4.3 = " << add(2.5, 4.3) << endl;

    // 문자열 합치기
    cout << "\"Hello, \" + \"World!\" = " << add(string("Hello, "), string("World!")) << endl;

    // 아래 코드는 컴파일 에러가 발생해야 함
    // cout << add(true, false) << endl;

    return 0;
}

 

  • 2-3 숙제 // 반복자로 컨테이너 순회
#include <iostream>
#include <vector>
#include <map>

using namespace std;

int main() {
    // 벡터와 맵 데이터 정의
    vector<int> vec = { 10, 20, 30, 40, 50 };
    map<string, int> mp = {
        {"Alice", 90},
        {"Bob", 85},
        {"Charlie", 95}
    };

    // 문제: 아래 부분을 완성하세요
    for (auto it = vec.begin(); it != vec.end(); it++) {
        cout << *it << " ";
    }
    cout << endl;
    for (auto it = vec.rbegin(); it != vec.rend(); it++) {
        cout << *it << " ";
    }
    cout << endl;
    for (auto it = mp.begin(); it != mp.end(); it++) {
        cout << it->first << ": " << it->second << endl;
    }
    for (auto it = mp.rbegin(); it != mp.rend(); it++) {
        cout << it->first << ": " << it->second << endl;
    }
    return 0;
}

zep 버그 ,, 책상에 갇히기! 책상 옆에서 찾아가기 기능을 계속 쓰면 책상 중간까지 텔레포트 할 수 있다..^^

 

'내배캠Unreal_TIL > C++' 카테고리의 다른 글

[TIL] 2025-12-18 | 과제3 구현 및 vector 동작 원리 이해  (0) 2025.12.18
[TIL] 2025-12-17 | C++ 예외 처리, 연산자 오버로드, 객체지향적 설계  (0) 2025.12.17
[TIL] 2025-12-15 | C++ 스마트 포인터, 템플릿  (0) 2025.12.15
[TIL] 2025-12-12 | 과제1 구현 및 입력 실패 처리, C++ 힙메모리  (0) 2025.12.12
[C++] Google C++ Style Guide, 구글 코드 컨벤션  (1) 2025.12.11
'내배캠Unreal_TIL/C++' 카테고리의 다른 글
  • [TIL] 2025-12-18 | 과제3 구현 및 vector 동작 원리 이해
  • [TIL] 2025-12-17 | C++ 예외 처리, 연산자 오버로드, 객체지향적 설계
  • [TIL] 2025-12-15 | C++ 스마트 포인터, 템플릿
  • [TIL] 2025-12-12 | 과제1 구현 및 입력 실패 처리, C++ 힙메모리
윤윤씨
윤윤씨
🎮 내일배움캠프 Unreal 7기
  • 윤윤씨
    컴퓨터온열맛사지
    윤윤씨
  • 전체
    오늘
    어제
    • 분류 전체보기 (62) N
      • 내배캠Unreal_TIL (62) N
        • C++ (23)
        • UE (31) N
        • 팀프로젝트 (7)
      • etc (0)
  • 블로그 메뉴

    • 홈
    • 태그
    • 방명록
  • 링크

    • Github
    • Solved.ac
    • YouTube
  • 태그

    디자인패턴
    프로그래머스
    gas
    챌린지
    언리얼과제
    STL
    스테이트머신
    ta
    머티리얼
    코드카타
    오토마타
  • 최근 댓글

  • hELLO· Designed By정상우.v4.10.6
윤윤씨
[TIL] 2025-12-16 | C++ STL, vector, map, sort(), find(), Iterator
상단으로

티스토리툴바