Home > Articles > Programming > C/C++

How C++11 Helps You Boost Your Developer Productivity

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.
Like this article? We recommend

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:


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:


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!

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information

To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.


Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.


If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information

Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.


This site is not directed to children under the age of 13.


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information

If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information

Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents

California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure

Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact

Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice

We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020