네, 주어진 코드에서 인덱스 범위를 벗어나는 문제가 발생할 가능성이 있습니다. 주요 원인은 다음과 같습니다.


1. max_elementmin_element 호출 후 인덱스 접근 문제

cpp
복사편집
max = max_element(people.begin(), people.end()) - people.begin();
boat += people.at(max);
people.erase(people.begin() + max);

2. while(check >= people.at(min)) 루프 내에서 빈 벡터 접근 가능성

cpp
복사편집
while (check >= people.at(min)) {


해결 방법

  1. 벡터가 비어 있는지 확인 후 min_element, max_element 호출하기

    people.empty()를 먼저 체크하고 min_elementmax_element를 호출하면, 빈 벡터에서 잘못된 인덱스를 구하는 문제를 방지할 수 있습니다.

  2. min_element 또는 max_element 호출 후 인덱스가 올바른지 확인

    people.erase() 호출 후 벡터 크기가 변하므로, 그 이후에 다시 min_element를 호출할 때 크기를 체크해야 합니다.

  3. while 루프 조건을 !people.empty()로 추가

    people.at(min) 접근 전에 people.empty() 여부를 체크하면, 빈 벡터에서 인덱스를 참조하는 문제를 해결할 수 있습니다.

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

using namespace std;

int solution(vector<int> people, int limit) {
    int boat = 0;  // 초기화 안 되어 있던 변수 초기화
    int answer = 0;
    int len = people.size();
    int check = limit;

    // 가벼운 순서로 정렬
    sort(people.begin(), people.end());

    // people이 빌 때까지 반복
    while (!people.empty()) {  // size() 체크보다 empty()가 더 안전함
        // 탑승 가능한 사람 중 가장 무거운 사람부터 태우기
        for (int i = people.size() - 1; i >= 0; i--) {
            if (people[i] <= check) {
                boat += people[i];
                people.erase(people.begin() + i);
                check = limit - boat;
            }
        }

        // 남은 무게, 남은 사람 수 갱신
        check = limit - boat;
        len = people.size();

        // 더 탈 수 있는 사람이 없어지면 보트 출발
        if (!people.empty() && check < people[0]) {  
            boat = 0;
            answer++;
            check = limit;
        }

        // 남은 사람이 없으면 루프 종료
        if (people.empty()) {
            answer++;  // 마지막 보트 출발
            break;
        }
    }

    return answer;
}

✅ 해결된 점