// This file contains some examples of using features of C++ that we would // describe as functional programming, including the use of anonymous functions // or lambdas. #include #include #include #include #include #include using namespace std; // used to display the contents of a vector template string to_string(T t) { ostringstream out; auto itr = t.begin(); out << "["; if (itr != t.end()) { out << *itr; itr++; while (itr != t.end()) { out << ", " << *itr; itr++; } } out << "]"; return out.str(); } // this defines a named function for comparing two strings and ordering them by // their length bool less_length(const string & s1, const string & s2) { return s1.length() < s2.length(); } int main() { vector words {"four", "score", "and", "seven", "years", "ago", "our", "fathers", "brought", "forth", "on", "this", "continent", "a", "new", "nation", "conceived", "in", "liberty", "and", "dedicated", "to", "the", "proposition", "that", "all", "men", "are", "created", "equal"}; cout << "words before sort = " << to_string(words) << endl; sort(words.begin(), words.end()); cout << "words after sort = " << to_string(words) << endl; stable_sort(words.begin(), words.end(), less_length); cout << "words after custom sort = " << to_string(words) << endl; cout << endl; // lambdas--anonymous functions string s = "Hello THerE!"; for_each(s.begin(), s.end(), [](char ch){cout << ch << endl;}); for_each(s.begin(), s.end(), [](char & ch){ch = tolower(ch);}); cout << "s = " << s << endl; cout << endl; vector numbers1 {3, 18, 7, 22, 3, 10, -2, 23, 52, 7, 9, 6, 14}; cout << "numbers1 = " << to_string(numbers1) << endl; int sum = accumulate(numbers1.begin(), numbers1.end(), 0); cout << "sum of numbers1 = " << sum << endl; int product = accumulate(numbers1.begin(), numbers1.end(), 1, multiplies()); cout << "product of numbers1 = " << product << endl; cout << endl; vector numbers2; copy_if(numbers1.begin(), numbers1.end(), back_inserter(numbers2), [](int n){return n % 3 == 0;}); cout << "numbers2 = " << to_string(numbers2) << endl; int max; cout << "max int? "; cin >> max; vector numbers3; auto f = [&max](int n){return n <= max;}; max = max - 10; copy_if(numbers1.begin(), numbers1.end(), back_inserter(numbers3), f); cout << "numbers3 = " << to_string(numbers3) << endl; cout << endl; return 0; }