Skip to content

Instantly share code, notes, and snippets.

@suminb
Created October 23, 2011 00:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save suminb/1306682 to your computer and use it in GitHub Desktop.
Save suminb/1306682 to your computer and use it in GitHub Desktop.
My First C++0x (C++11) Program
#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;
}
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)
@suminb
Copy link
Author

suminb commented Oct 23, 2011

Installed gcc46 (GCC 4.6) in Macports. hello_c++0x.cpp can be compiled as following:

g++-mp-4.6 -std=c++0x hello_c++0x.cpp

hello_python.py demonstrates how the same task can be done in Python.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment