공부/Code Cata

람다 함수로 사용자 설정 정의해 정렬하기

동그래님 2025. 1. 1. 13:43

 

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

using namespace std;

vector<string> solution(vector<string> strings, int n) 
{
    sort(strings.begin(), strings.end(), [n](const string& a, const string& b) {
        if(a[n] == b[n])
        {
            return a < b;
        }
        return a[n] < b[n];
    });
    
    return strings;
}

비교할 인덱스 값 n을 capture해서 람다 함수로 넘겨주어 두 인덱스의 값이 같다면 사전순으로 정렬하고, 같지 않다면 바로 오름차순 정렬하였다.

 

람다함수

[capture](parameters) -> return_type {
    // function body
};
  • capture: 람다 함수 외부의 변수를 가져오는 방식이다. [ ] 안에 변수나 참조를 명시한다.
  • parameters: 일반 함수와 동일하게 함수의 매개변수 목록이다.
  • function body: 람다 함수의 실행 코드를 작성
  1. 람다 함수는 익명 함수(anonymous function)을 정의할 때 사용하는 간단한 문법이다.
  2. 일반 함수와 동일한 작업을 수행하지만, 이름이 없고 간결하게 작성할 수 있다는 장점이 있다.
  3. 주로 짧은 코드나 일회성 사용을 목적으로 사용된다.
  4. capture에 외부 지역 변수를 캡쳐해서 쉽게 사용할 수 있다.

*caputre 없이 vector에 있는 정수 정렬

더보기
vector<int> Array = { 3,9,2,0,5,7 };

sort(Array.begin(), Array.end(), [](const int& a, const int& b) {return a < b; });

 

*capture에 변수의 레퍼런스를 전달해서 vector의 누적 값 구하기

더보기
vector<int> Vector = { 1,2,3,4,5 };
int Total = 0;

for_each(Vector.begin(), Vector.end(), [&Total](const int& Value) {Total += Value; });

cout << Total;