C++ 공부

25.10.05 연습문제 풀이 (범위 기반 반복문)

Client Side 2025. 10. 7. 21:21

연습문제 1 : 구조체 정렬 (람다식 & 범위 기반 반복문 활용) 

 

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

using namespace std;

// 책 정보를 담는 구조체
struct Book {
    string title;
    int pages;
};

int main() {
    vector<Book> books = {
        {"C++ Programming", 500},
        {"Data Structures", 350},
        {"Algorithms", 420},
        {"Effective C++", 200},
        {"Clean Code", 400}
    };
    
    cout << "--- 정렬 전 ---" << endl;
    for (const auto& book : books) {
        cout << "제목: " << book.title << ", 페이지: " << book.pages << endl;
    }
    cout << endl;

    
    // 여기에 코드 작성

    cout << "--- 페이지 오름차순 정렬 후 ---" << endl;
    for (const auto& book : books) { 
        cout << "제목: " << book.title << ", 페이지: " << book.pages << endl;
    }
    cout << endl;
    
    return 0;
}

 

문제풀이 :

    // 람다식으로 페이지 수 오름차순 정렬
    sort(books.begin(), books.end(), [](const Book& a, const Book& b) {
        return a.pages < b.pages;  // 페이지 수 적은 순으로 정렬
    });

 

 

 

연습문제 2 : 2차원 그리드 탐색 (2차원 벡터 & 범위 기반 반복문 & 조건문)

#include <iostream>
#include <vector>
#include <string> 

using namespace std;

int main() {
    // 간단한 미로 (맵)
    vector<string> grid = {
        "#####",
        "#S  #",
        "# # #",
        "# E #",
        "#####"
    }; // S는 시작점, E는 끝점, #은 벽

    int start_row = -1;
    int start_col = -1;
    int end_row = -1;
    int end_col = -1;
    

    // 여기에 코드 작성

    cout << "시작점 (S): (" << start_row << ", " << start_col << ")" << endl;
    cout << "도착점 (E): (" << end_row << ", " << end_col << ")" << endl;
    
    return 0;
}

 

문제풀이 :

 

일반 반복문을 통한 방법

    for (int row = 0; row < grid.size(); ++row)
        {
            for (int col = 0; col < grid[row].size(); ++col)
                {
                    if (grid[row][col] == 'S')
                    {
                        start_row = row;
                        start_col = col;
                    }
                    else if (grid[row][col] == 'E')
                    {
                        end_row = row;
                        end_col = col;
                    }
                }
        }

 

 

범위 기반 반복문을 통한 방법

    int current_row = 0; // 현재 행의 인덱스를 저장할 변수
    for (const auto& row_str : grid) { // 각 행(string 타입)에 대해 반복
        int current_col = 0; // 현재 열의 인덱스를 저장할 변수
        for (const auto& cell_char : row_str) { // 각 행의 문자(char 타입)에 대해 반복
            if (cell_char == 'S') {
                start_row = current_row;
                start_col = current_col;
            } 
            else if (cell_char == 'E') {
                end_row = current_row;
                end_col = current_col;
            }
            current_col++; // 다음 열로 이동
        }
        current_row++; // 다음 행으로 이동
    }

'C++ 공부' 카테고리의 다른 글

소수 판별하기  (0) 2025.10.31
N번째 큰 수 찾기 (std::nth_element)  (0) 2025.10.24
범위 기반 반복문 (Range-based for loop)  (0) 2025.10.05
istringstream  (1) 2025.10.01
최대공약수와 최소공배수를 구하는 함수  (0) 2025.09.29