Want more features on Pastebin? Sign Up, it's FREE!
Guest

Blocks as Lambda for C++

By: a guest on Dec 2nd, 2011  |  syntax: C++  |  size: 0.92 KB  |  views: 88  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. // Code from http://msdn.microsoft.com/en-us/library/dd293608.aspx, adapted to use Apple's blocks extension
  2.  
  3. #include <algorithm>
  4. #include <iostream>
  5. #include <vector>
  6. using namespace std;
  7.  
  8. int main()
  9. {
  10.    // Create a vector object that contains 10 elements.
  11.    vector<int> v;
  12.    for (int i = 0; i < 10; ++i)  {
  13.       v.push_back(i);
  14.    }
  15.  
  16.    // Count the number of even numbers in the vector by
  17.    // using the for_each function and a lambda expression.
  18.    __block int evenCount = 0;
  19.    for_each(v.begin(), v.end(), ^(int n) {
  20.       cout << n;
  21.  
  22.       if (n % 2 == 0)
  23.       {
  24.          cout << " is even " << endl;
  25.  
  26.          // Increment the counter.
  27.          evenCount++;
  28.       }
  29.       else
  30.       {
  31.          cout << " is odd " << endl;
  32.       }
  33.    });
  34.  
  35.    // Print the count of even numbers to the console.
  36.    cout << "There are " << evenCount
  37.         << " even numbers in the vector." << endl;
  38. }
  39.  
  40.  
clone this paste RAW Paste Data