우당탕탕 개발일지

[프로그래머스] Level 1. 데이터 분석 본문

Algorithm(c++)/Level 1

[프로그래머스] Level 1. 데이터 분석

devchop 2025. 1. 16. 16:44

 

https://school.programmers.co.kr/learn/courses/30/lessons/250121

 

프로그래머스

SW개발자를 위한 평가, 교육, 채용까지 Total Solution을 제공하는 개발자 성장을 위한 베이스캠프

programmers.co.kr

 

이 문제는 해결 방법이 어렵지는 않은데, c++ 에 대한 문법이해가 필요한 문제였다. 

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

using namespace std;

bool compare(vector<int> a , vector<int> b , string sort_by){
    return true;
    
}
vector<string> keys = {"code","date","maximum","remain"};

vector<vector<int>> solution(vector<vector<int>> data, string ext, int val_ext, string sort_by) {
    
    vector<vector<int>> answer;
    for(int i = 0 ; i< data.size(); i++){
        int data_value = data[i][find(keys.begin(), keys.end(), ext)-keys.begin()];
        if(data_value < val_ext) answer.push_back(data[i]);
    }
    
    int index = find(keys.begin(), keys.end(), sort_by) - keys.begin();
    sort(answer.begin(), answer.end(), [&index](const vector<int>& a , const vector<int>& b){
        
        return a[index] <= b[index];
    });
    
    return answer;
}

 

변수 이름을 담은 문자열을 선언하고, ext를 이용해 인덱스를 찾아 data의 값에 접근 할 수 있다.

중요한 것은, 정렬 시 index값을 필요로 하는데,  그냥 가져다 사용할 수 없다. 아래처럼 &index 키워드를 이용해야 한다. 

 

[&index](const vector<int>& a, const vector<int>& b) {
    return a[index] <= b[index];
}

 

위 구문은 람다함수로, [] 를 사용하여 외부 변수를 캡처하고 람다 함수 안에서 사용할 수 있다. 

index 라는 외부변수를 참조로 캡처한다. 만약 모든 외부변수를 캡처하고 싶다면, [&] 라고 입력한다. 매개변수 a 와 b 는 const 로 선언되어 수정되지 않도록 보장한다.