Skip to content

Instantly share code, notes, and snippets.

@vaclavbohac
Created September 2, 2011 14:01
Show Gist options
  • Select an option

  • Save vaclavbohac/1188657 to your computer and use it in GitHub Desktop.

Select an option

Save vaclavbohac/1188657 to your computer and use it in GitHub Desktop.
Example of the lambda functions in c++0x
// Copyright 2011 Vaclav Bohac <[email protected]>. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS-IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <cstdlib>
#include <iostream>
#include <functional>
using namespace std;
/**
* Invokes fn for each number.
* @param int* beginning of the array
* @param int length of the array
* @param void(int) callback function
* @return void
*/
void each(int* numbers, int length, function<void(int)> fn) {
int i, l = length > 0 ? length : 0;
for (i = 0; i < l; i++) {
fn( numbers[i] );
}
}
int main() {
int sum = 0, nums[] = {1, 2, 3},
l = sizeof(nums) / sizeof(int);
each(nums, l, [&](int number) {
sum += number; // Sum is closured and writeable.
});
cout << sum << endl; // Prints 6
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment