Home > Articles > Programming > C/C++

How C++11 Helps You Boost Your Developer Productivity

  • Print
  • + Share This
  • 💬 Discuss
Programming languages come into vogue and then fade away. Meanwhile, C++ keeps going strong. Siddhartha Rao, author of Sams Teach Yourself C++ in One Hour a Day, 7th Edition, is convinced that the latest revision called C++11 boosts your productivity in coding easy-to-understand and powerful C++ applications. Here he explains features that simplify your programming tasks, and he supplies an overview of the major improvements C++11 has to offer.

Interesting and ironic as it might seem, in spite of being one of the oldest object-oriented programming languages in use, C++ continues to give developers new ways to write productive and powerful applications. This is largely due to the new version called C++11, ratified by the ISO committee in 2011.

In this article, which contains snippets from my new book, Sams Teach Yourself C++ in One Hour a Day, 7th Edition, I will briefly introduce some advantages that C++11 offers you as a developer of C++ applications.

We'll start with the simplest and possibly the most intuitive feature new to C++11—the keyword auto, which allows you the flexibility of not declaring the explicit type (without compromising on type safety). Then we'll analyze the completely new concept of lambda functions, before concluding with a note on few features that help you to write high-performance applications using C++11.

Using the auto Keyword

This is the typical syntax for variable initialization in C++:

VariableType VariableName = InitialValue;

This syntax indicates that you're required to know the type of the variable you're creating. In general, it's good to know the type of your variable; however, in many situations the compiler can accurately tell the best type that suits your variable, given the initialization value. For example, if a variable is being initialized with the value true, the type of the variable can surely be best estimated as bool. C++11 gives you the option of not explicitly specifying the type when you use the keyword auto instead:

auto Flag = true; // let compiler select type (bool)

The keyword auto thus delegates the task of defining an exact type for the variable Flag to the compiler. The compiler checks the nature of the value to which the variable is being initialized, and then it decides the best possible type that suits this variable. In this particular case, it's clear that an initialization value of true best suits a variable of type bool. The compiler henceforth treats variable Flag as a bool.

How is auto a productivity improvement for you as a developer? Let's analyze the user of auto for the non-POD (Plain Old Data) types, say in iterating a vector of integers:

std::vector<int> MyNumbers;

Iterating this vector of integers in a for loop conveys the crazy complexity of STL programming:

for ( vector<int>::const_iterator Iterator = MyNumbers.begin();
      Iterator < MyNumbers.end();
      ++Iterator )
   cout << *Iterator << " ";

With C++11, creating a loop that iterates the contents of a Standard Template Library (STL) container is much easier to read and hence understand:

for( auto Iterator = MyNumbers.cbegin();
     Iterator < MyNumbers.cend();
     ++Iterator )
   cout << *Iterator << " ";

Thus, auto is not only about letting the compiler choose the type that suits best; it also helps you to write code that's significantly more compact and friendly to read.

Working with Lambda Functions

Lambda functions are particularly useful to programmers who frequently use STL algorithms. Also called lambda expressions, they can be considered as functions without a name; that is, anonymous functions. Depending on their use, lambda expressions can also be visualized as a compact version of an unnamed struct (or class) with a public operator().

The general syntax for definition of a lambda function is as follows:

[optional capture list](Parameter List) {// lambda code here;}

To understand how lambdas work and how they help improve productivity, let's analyze a simple task: displaying the contents of a container using STL's for_each() algorithm. for_each() takes a range and a unary function that operates on that range. Let's first write this code using the C++98 techniques of defining a unary function (Case 1) and then a function object or functor (Case 2), and finally using the new C++11 technique of lambda expressions (Case 3).

Case 1 (C++98): A regular function DisplayElement() that displays an input parameter of type T on the screen using std::cout:

template <typename T>
void DisplayElement (T& Element)
{
   cout << Element << ' ';
}

Using it in for_each() to display integers contained in a vector:

for_each(MyNumbers.begin(),MyNumbers.end(),DisplayElement<int>);

Case 2 (C++98): A function object that helps display elements in a container:

template <typename elementType>
struct DisplayElement
{
      void operator () (const elementType& element) const
      {
            cout << element << ' ';
      }
};

Using this functor in for_each() to display integers in a vector:

for_each(MyNumbers.begin(),MyNumbers.end(),DisplayElement<int>());

Case 3 (C++11): Using lambda functions to display the contents of a container.

The lambda expression will compact the entire code, including the definition of the unary predicate, into the for_each() statement itself:

for_each (Container.begin(),Container.end(),
         [](int Element) {cout << Element << ' ';} );

Conclusion: Clearly, using lambda functions saved many lines of code. Importantly, the for_each() expression is self-explanatory, without requiring the reader to jump to another location that defines the unary function.

Thus, here's a little application that can display the contents of a vector<int> and a list<char> using for_each() and a lambda within it:

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

using namespace std;

int main ()
{
   vector <int> vecIntegers;

   for (int nCount = 0; nCount < 10; ++ nCount)
      vecIntegers.push_back (nCount);

   list <char> listChars;
   for (char nChar = 'a'; nChar < 'k'; ++nChar)
      listChars.push_back (nChar);

   cout << "Displaying vector of integers using a lambda: " << endl;

   // Display the array of integers
   for_each ( vecIntegers.begin ()    // Start of range
            , vecIntegers.end ()        // End of range
            , [](int& element) {cout << element << ' '; } ); // lambda

   cout << endl << endl;
   cout << "Displaying list of characters using a lambda: " << endl;

   // Display the list of characters
   for_each ( listChars.begin ()        // Start of range
            , listChars.end ()        // End of range
            , [](char& element) {cout << element << ' '; } ); // lambda

   cout << endl;

   return 0;
}

Here's the output of this application:

Displaying vector of integers using a lambda:
0 1 2 3 4 5 6 7 8 9

Displaying list of characters using a lambda:
a b c d e f g h i j

Lambdas are not restricted to substituting unary functions only, as seen above. For example, they can also be used to create unary predicates to be used in find_if() algorithms, or binary predicates to be used in std::sort() algorithms.

A lambda can also interact with variables outside of the scope of the function that contains it. If you're wondering how the "optional capture list" is used, now you know—the optional capture list informs the lambda about variables from outside its own scope that it can use!

Consider that you have a vector of integers. If the user was to supply a Divisor and your task was to find the first element in this vector that was divisible by the user-supplied Divisor, you can program a unary lambda expression inside a find_if to help you with the task:

int Divisor;
cin >> Divisor;

auto iElement = find_if ( vecIntegers.begin (),
                        vecIntegers.end (),
                        [Divisor](int dividend){return (dividend % Divisor) == 0;});

The lambda function above recognizes a Divisor that was defined outside of its scope, yet captured via the capture list [...].

Following is a complete sample that allows a user to input a Divisor and finds the first element in a container that is completely divisible by it:

#include <algorithm>
#include <vector>
#include <iostream>
using namespace std;

int main ()
{
   vector <int> vecIntegers;
   cout << "The vector contains the following sample values: ";

   // Insert sample values: 25 - 31
   for (int nCount = 25; nCount < 32; ++ nCount)
   {
      vecIntegers.push_back (nCount);
      cout << nCount << ' ';
   }
   cout << endl << "Enter divisor (> 0): ";
   int Divisor = 2;
   cin >> Divisor;

   // Find the first element that is a multiple of divisor
   auto iElement = find_if ( vecIntegers.begin (),
                      vecIntegers.end (),
              [Divisor](int dividend){return (dividend % Divisor) == 0; } );

   if (iElement != vecIntegers.end ())
   {
      cout << "First element in vector divisible by " << Divisor;
      cout << ": " << *iElement << endl;
   }

   return 0;
}

Here's the output:

The vector contains the following sample values: 25 26 27 28 29 30 31
Enter divisor (> 0): 3
First element in vector divisible by 3: 27

It's beyond the scope of this little article to fully explain the wonders of lambda expressions. This topic is discussed in great detail in a dedicated lesson in Sams Teach Yourself C++ in One Hour a Day, 7th Edition. You can download the code samples from the lesson on lambda expressions, which also demonstrate how lambdas can be used as binary functions in std::transform and as binary predicates in std::sort(), among other features specific to C++11.

Other C++11 Productivity and Performance Features

The following C++11 features (and many others) are explained in detail in Sams Teach Yourself C++ in One Hour a Day, 7th Edition, which also contains do's and don'ts at the end of each lesson to keep you on the right path:

  • Move constructors and move assignment operators help avoid unnecessary, unwanted, and previously unavoidable copy steps, improving the performance of your application
  • New smart pointer std::unique_ptr supplied by header <memory> allows neither copy nor assignment (std::auto_ptr is deprecated)
  • static_assert allows the compiler to display an error message when a compile-time parameter check has failed
  • Keyword constexpr (constant expression) allows you to define a compile-time constant function

On this note, I wish you success with programming your next application using C++11. I look forward to your comments and feedback. Thank you!

  • + Share This
  • 🔖 Save To Your Account

Discussions

comments powered by Disqus