C++11!

20 Feb 2014

These things make me excited to program in C++ again (which I already do for a living).

auto

/* C++98/03 */

// Pretend the vector has stuff in it.
vector<int> ents;
int sum = 0;
for (vector<int>::const_iterator iter = ents.begin(); iter != ents.end(); ++iter) {
    sum += *iter;
}

/* C++11 */

// Pretend the vector has stuff in it.
// Although you won't have to with initializer lists...
vector<int> ents;
int sum = 0;
for (auto iter = ents.begin(); iter != ents.end(); ++iter) {
    sum += *iter;
}

foreach

/* C++98/03 */

// Keep pretending.
vector<int> ents;
int sum = 0;
for (vector<int>::const_iterator iter = ents.begin(); iter != ents.end(); ++iter) {
    sum += *iter;
}

/* C++11 */

// Keep pretending.
vector<int> ents;
int sum = 0;
for (int i : ents) {
    sum += i;
}

// Or, you could auto that int
for (auto i : ents) {
    sum += i;
}

initializer lists

/* C++98/03 */

// Keep pretending.
vector<int> ents;
int sum = 0;
for (vector<int>::const_iterator iter = ents.begin(); iter != ents.end(); ++iter) {
    sum += *iter;
}

/* C++11 */

// finally!
vector<int> ents = { 1, 2, 3, 4 };
int sum = 0;
for (int i : ents) {
    sum += i;
}

// Some more cool initializer list stuff
map<set<string>, vector<string>> tldr = {
    { {"this", "is", "cool"}, {"I", "know", "right"} },
    { {"anyways"}, {"giggity", "giggity", "giggity"} }
};

lambdas

/* C++98/03 */

struct Sum
{
    int *m_sum;
    Sum(int *sum)
    {
        m_sum = sum;
    }
    void operator() (int i)
    {
        *m_sum += i;
    }
};
// Keep pretending.
vector<int> ents;
int sum = 0;
for_each(ents.begin(), ents.end(), Sum(&sum));

/* C++11 */

vector<int> ents = { 1, 2, 3, 4 };
int sum = 0;
for_each(ents.begin(), ents.end(), [&sum](int i){ sum += i; });

constructors

/* C++98/03 */

class Foo
{
public:
    Foo(const string &str)
    {
        bar(str);
    }
    Foo(const string &str, int i)
    {
        bar(str);
        git(i);
    }
};

Foo foo("string");
Foo bar("string", 3);

/* C++11 */

class Foo
{
public:
    Foo(const string &str)
    {
        bar(str);
    }
    Foo(const string &str, int i)
        : Foo(str)
    {
        git(i);
    }
};

Foo foo("string");
Foo bar("string", 3);

member initialization

/* C++98/03 */

class Foo
{
private:
    string m_str;
    int m_i;
public:
    Foo(const string &str)
        : m_str("C++ ")
        , m_i(98)
    {
        bar(str);
    }
    Foo(const string &str, int i)
        : m_str("C++ ")
        , m_i(98)
    {
        bar(str);
        git(i);
    }
};

Foo foo("string");
Foo bar("string", 3);

/* C++11 */

class Foo
{
private:
    string m_str = "C++ ";
    int m_i = 11;
public:
    Foo(const string &str)
    {
        bar(str);
    }
    Foo(const string &str, int i)
        : Foo(str)
    {
        git(i);
    }
};

Foo foo("string");
Foo bar("string", 3);

For more, check out Stroustrup’s FAQ webpage