Created
September 26, 2015 21:08
-
-
Save dmitru/3f851dc2ac873ed01f8e to your computer and use it in GitHub Desktop.
An example showing how to use some functional constructs in C++
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
#include <string> | |
#include <vector> | |
int main() | |
{ | |
// Enter lambda functions.. | |
auto sum = [] (int x, int y) { | |
std::cout << "Hello, side-effects!" << std::endl; | |
return x + y; | |
}; | |
std::cout << "1 + 2 = " << sum(1, 2) << std::endl; | |
// Accessing outer scope from lambdas | |
std::vector<int> vec = {1, 2, 3, 4, 5}; | |
([&vec] (int i) { vec.push_back(i); })(42); | |
// Dump the vector to see that its content has changed: | |
for (auto el : vec) | |
std::cout << el << ' '; | |
std::cout << std::endl; | |
// any_of, all_of, find_if | |
auto is_any_even = std::any_of(vec.begin(), vec.end(), [] (int el) {return el % 2 == 0;}); | |
auto all_less_than_ten = std::all_of(vec.begin(), vec.end(), [] (int el) {return el < 10;}); | |
auto first_non_even = std::find_if(vec.begin(), vec.end(), [] (int el) {return el % 2 != 0;}); | |
std::cout << "First non_even is " << *first_non_even << std::endl; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment