http://vsts2010.tistory.com/80
람다 식 외부에 정의되어 있는 변수를 람다 식 내에서 사용한 후 결과를 그 변수에 그대로 저장하고 싶을 때가 있습니다. 이럴 때 클로져를 사용하면 됩니다.
[code]
[](파라메터) { 식 }
[/code]
[code]
int main()
{
vector< int > Moneys;
Moneys.push_back( 100 );
Moneys.push_back( 4000 );
Moneys.push_back( 50 );
Moneys.push_back( 7 );
int TotalMoney1 = 0;
for_each(Moneys.begin(), Moneys.end(), [&TotalMoney1](int Money) {
TotalMoney1 += Money;
});
cout << "Total Money 1 : " << TotalMoney1 << endl;
return 0;
}
[/code]
복수의 변수를 캡쳐
[code]
[ &Numb1, &Numb2 ]
[/code]
‘[&]’로 하면람다 식을 정의한 범위 내에 있는 모든 변수를 캡쳐할 수 있습니다
[code]
for_each(Moneys.begin(), Moneys.end(), [&](int Money) {
TotalMoney1 += Money;
if( Money > 1000 ) TotalBigMoney += Money;
});
cout << "Total Money 1 : " << TotalMoney1 << endl;
cout << "Total Big Money : " << TotalBigMoney << endl;
[/code]
클래스 멤버 내의 람다 식은 해당 클래스에서는 friend로 인식하므로 람다 식에서 private 멤버의 접근도 할 수 있습ㄴ다.
그리고 클래스의 멤버를 호출할 때는 ‘this’를 캡쳐합니다
[code]
class NetWork
{
public:
NetWork()
{
SendPackets.push_back(10);
SendPackets.push_back(32);
SendPackets.push_back(24);
}
void AllSend() const
{
for_each(SendPackets.begin(), SendPackets.end(), [this](int i){ Send(i); });
}
private:
vector< int > SendPackets;
void Send(int PacketIndex) const
{
cout << "Send Packet Index : " << PacketIndex << endl;
}
};
int main()
{
NetWork().AllSend();
return 0;
}
[/code]
람다 식 외부에 정의되어 있는 변수를 람다 식 내에서 사용한 후 결과를 그 변수에 그대로 저장하고 싶을 때가 있습니다. 이럴 때 클로져를 사용하면 됩니다.
[code]
[](파라메터) { 식 }
[/code]
[code]
int main()
{
vector< int > Moneys;
Moneys.push_back( 100 );
Moneys.push_back( 4000 );
Moneys.push_back( 50 );
Moneys.push_back( 7 );
int TotalMoney1 = 0;
for_each(Moneys.begin(), Moneys.end(), [&TotalMoney1](int Money) {
TotalMoney1 += Money;
});
cout << "Total Money 1 : " << TotalMoney1 << endl;
return 0;
}
[/code]
복수의 변수를 캡쳐
[code]
[ &Numb1, &Numb2 ]
[/code]
‘[&]’로 하면람다 식을 정의한 범위 내에 있는 모든 변수를 캡쳐할 수 있습니다
[code]
for_each(Moneys.begin(), Moneys.end(), [&](int Money) {
TotalMoney1 += Money;
if( Money > 1000 ) TotalBigMoney += Money;
});
cout << "Total Money 1 : " << TotalMoney1 << endl;
cout << "Total Big Money : " << TotalBigMoney << endl;
[/code]
클래스 멤버 내의 람다 식은 해당 클래스에서는 friend로 인식하므로 람다 식에서 private 멤버의 접근도 할 수 있습ㄴ다.
그리고 클래스의 멤버를 호출할 때는 ‘this’를 캡쳐합니다
[code]
class NetWork
{
public:
NetWork()
{
SendPackets.push_back(10);
SendPackets.push_back(32);
SendPackets.push_back(24);
}
void AllSend() const
{
for_each(SendPackets.begin(), SendPackets.end(), [this](int i){ Send(i); });
}
private:
vector< int > SendPackets;
void Send(int PacketIndex) const
{
cout << "Send Packet Index : " << PacketIndex << endl;
}
};
int main()
{
NetWork().AllSend();
return 0;
}
[/code]
'Native > C++' 카테고리의 다른 글
base36 encode/decode (0) | 2013.10.02 |
---|---|
Very very useful: eBooks compiled from top StackOverflow topics/answers (0) | 2013.10.02 |
c++0x lamda (0) | 2013.10.02 |
c++0x rvalue reference (0) | 2013.10.02 |
c++0x auto (0) | 2013.10.02 |