람다와 캡처
Coddy의 C 개발자를 위한 C++ 코스 레슨. 48개 중 24번째.
C 콜백은 상태를 위해 void 포인터 컨텍스트를 받는 경우가 많습니다. C++ 람다는 주변 변수를 명시적으로 캡처할 수 있습니다. 값 캡처는 복사본을 저장하고, 참조 캡처는 원래 객체를 참조하지만 객체보다 오래 유지되어서는 안 됩니다. 상태가 없는 람다와 변수를 캡처한 클로저에는 서로 다른 변환 규칙이 적용됩니다.
C
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>
int offset(int x,const int* context){return x+*context;}
int main(void){
int context=2;printf("%d\n",offset(3,&context));
return 0;
}
C++
#include <iostream>
#include <string>
#include <vector>
#include <array>
#include <map>
#include <set>
#include <algorithm>
#include <memory>
#include <sstream>
#include <stdexcept>
#include <utility>
int main(){
int n=2;auto f=[n](int x){return x+n;};n=9;std::cout<<f(3)<<"\n";
}
각 프로그램을 독립적으로 추적하세요. 이 예제들은 과제와 다른 연산이나 데이터를 사용해 개념을 보여 줍니다. 소스 출력과 대상 출력이 일치한다고 가정하지 마세요.
챌린지
쉬움입력: 첫 번째 줄에는 threshold가, 두 번째 줄에는 정수들이 있습니다. threshold보다 엄격히 큰 값의 개수를 반환하세요.
exercise.hpp와 exercise.cpp에 선언된 API를 구현하세요. 두 파일 모두 수정할 수 있습니다. 공개 시그니처는 그대로 유지하세요. 잠긴 main.cpp는 표준 입력을 읽고 API를 직접 호출합니다. 또한 명시된 경우 공개 API의 동작도 독립적으로 확인합니다. API 내부에서 출력하지 말고 값을 반환하세요. 정수 입력값과 결과는 부호 있는 int 범위에 들어가며, 별도로 명시되지 않는 한 텍스트는 ASCII입니다.
직접 해보기
#include "exercise.hpp"
#include <iostream>
int main(){
std::vector<std::string> rows; std::string line; while(std::getline(std::cin,line)) rows.push_back(line);
int t=std::stoi(rows[0]);std::istringstream in(rows.size()>1?rows[1]:"");std::vector<int>v;int n;while(in>>n)v.push_back(n);std::cout<<above(v,t)<<"\n";
}
이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.
C 개발자를 위한 C++의 모든 레슨
직접 연습해 보세요: 온라인 C++ 컴파일러