Advertisement
Guest User

Blocks as Lambda for C++

a guest
Dec 2nd, 2011
102
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.92 KB | None | 0 0
  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.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement