C++11

For my current contract I finally have access to a C++11 compiler, and am starting to use C++11 in a production environment. Yes, I’m late to the party but that’s what happens when you have a succession of clients using older compilers.

I’m only scratching the surface so far, but things I am really liking so far are the auto keyword, initialiser lists, and the extensions to the for command to make iteration more compact.

Consider the following traditional C++ code for initialising a vector and then iterating over it:

std::vector<int> myVector;
myVector.push_back(1);
myVector.push_back(2);
myVector.push_back(3);
myVector.push_back(4);
myVector.push_back(5);

for (std::vector<int>::const_iterator it = myVector.begin(); it != myVector.end(); ++it)
    std::cout << *it << std::endl;

Now consider the same code written in C++11

std::vector<int> myVector = { 1, 2, 3, 4, 5 };

for (auto elem : myVector)
    std::cout << elem << std::endl;

Life just got a whole lot more convenient.

Update:

Note that for more complex types where there is a significant cost to copy, you would probably want to use the following instead:

for (const auto& elem : myVector)

About DataHamster

The Data Hamster stores facts and information in its capacious cheek pouches and regurgitates them from time to time.

Tagged , , , . Bookmark the permalink.

Leave a Reply