Vivek Haldar

The new C++

C++, and its programmers, may not be in the limelight (were they ever?), but they are the silent warriors that build the reliable and economical backends that make the shiny Web go. The language and libraries have been mostly the same for a while. But the new C++11 standard has brought many new features and a lot of excitement around the C++ scene.

Consider a totally toy example: print out the squares of numbers from 0 to 9. In “old” C++ this would look something like:

#include <iostream>
#include <list>
#include <algorithm>

using namespace std;

int square(int i) {
  return i * i;
}

int main() {
  list<int> l;
  for (int i = 0; i < 10; i++) {
    l.push_back(i);
  }

  list<int> t;
  t.resize(l.size());
  transform(l.begin(), l.end(), t.begin(), square);

  for (list<int>::iterator it = t.begin(); it != t.end(); ++it) {
    cout << " " << *it;
  }

return 0;
}

Using the new C++11 features (Range-based for loops! Lambda expressions! List initializers! Type inference!), that becomes somewhat shorter and cleaner, while not sacrificing an ounce of its grip on the bare metal:

#include <iostream>
#include <list>
#include <algorithm>

using namespace std;

int main() {
  list<int> l = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};

  list<int> t;
  t.resize(l.size());
  transform(l.begin(), l.end(), t.begin(),
        [](int i){ return i * i;});

  for (auto e : t) {
    cout << " " << e;
  }

  return 0;
}

Of course, detractors will say that none of that comes even close to the succint Python solution:

l = range(10)
t = [ x * x for x in l ]
for e in t:
  print e, ' ',

Note that a big win in terms of expressivity in the Python solution comes from list comprehensions. Perhaps the next C++?