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.

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!

 

资源下载链接为: https://pan.quark.cn/s/22ca96b7bd39 在当今的软件开发领域,自动化构建与发布是提升开发效率和项目质量的关键环节。Jenkins Pipeline作为一种强大的自动化工具,能够有效助力Java项目的快速构建、测试及部署。本文将详细介绍如何利用Jenkins Pipeline实现Java项目的自动化构建与发布。 Jenkins Pipeline简介 Jenkins Pipeline是运行在Jenkins上的一套工作流框架,它将原本分散在单个或多个节点上独立运行的任务串联起来,实现复杂流程的编排与可视化。它是Jenkins 2.X的核心特性之一,推动了Jenkins从持续集成(CI)向持续交付(CD)及DevOps的转变。 创建Pipeline项目 要使用Jenkins Pipeline自动化构建发布Java项目,首先需要创建Pipeline项目。具体步骤如下: 登录Jenkins,点击“新建项”,选择“Pipeline”。 输入项目名称和描述,点击“确定”。 在Pipeline脚本中定义项目字典、发版脚本和预发布脚本。 编写Pipeline脚本 Pipeline脚本是Jenkins Pipeline的核心,用于定义自动化构建和发布的流程。以下是一个简单的Pipeline脚本示例: 在上述脚本中,定义了四个阶段:Checkout、Build、Push package和Deploy/Rollback。每个阶段都可以根据实际需求进行配置和调整。 通过Jenkins Pipeline自动化构建发布Java项目,可以显著提升开发效率和项目质量。借助Pipeline,我们能够轻松实现自动化构建、测试和部署,从而提高项目的整体质量和可靠性。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值