Created
October 23, 2011 00:29
-
-
Save suminb/1306682 to your computer and use it in GitHub Desktop.
My First C++0x (C++11) Program
This file contains hidden or 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 <list> | |
using namespace std; | |
template <class T> | |
list<T> filter(bool (*f)(T x), list<T>* l) { | |
list<T> result; | |
typename list<T>::iterator it = l->begin(); | |
while(it != l->end()) { | |
if(f(*it)) result.push_back(*it); | |
it++; | |
} | |
return result; | |
} | |
template <class T> | |
list<T> map(T (*f)(T x), list<T>* l) { | |
list<T> result; | |
typename list<T>::iterator it = l->begin(); | |
while(it != l->end()) { | |
result.push_back(f(*it++)); | |
} | |
return result; | |
} | |
template <class T> | |
int reduce(T (*f)(T x, T y), list<T>* l) { | |
typename list<T>::iterator it = l->begin(); | |
T result = f(*it++, *it++); | |
while(it != l->end()) { | |
result = f(result, *it++); | |
} | |
return result; | |
} | |
int main() { | |
list<int> l; | |
for(int i=1; i<=5; i++) l.push_back(i); | |
cout << reduce<int>([](int x, int y) { return x + y; }, &l) << endl; | |
{ | |
list<int> p = map<int>([](int x) { return x * x; }, &l); | |
list<int>::iterator it = p.begin(); | |
while(it != p.end()) { | |
cout << *it++ << " "; | |
} | |
cout << endl; | |
} | |
{ | |
list<int> q = filter<int>([](int x) { return x % 2 == 0; }, &l); | |
list<int>::iterator it = q.begin(); | |
while(it != q.end()) { | |
cout << *it++ << " "; | |
} | |
cout << endl; | |
} | |
return 0; | |
} |
This file contains hidden or 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
l = range(1, 6) | |
print reduce(lambda x, y: x + y, l) | |
print map(lambda x: x*x, l) | |
print filter(lambda x: x%2 == 0, l) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Installed gcc46 (GCC 4.6) in Macports. hello_c++0x.cpp can be compiled as following:
hello_python.py
demonstrates how the same task can be done in Python.