Create More Readable and Concise C++ Code - dummies

Create More Readable and Concise C++ Code

By John Paul Mueller, Jeff Cogswell

One of the advantages of using C++ is that you can create concise code that is easy to read. Because you can see more of the code in one glance, C++ is often easier to understand as well because you don’t have to scroll the editor page to see the entire solution to a particular problem.

However, there are some types of C++ problems that did require a rather verbose solution in earlier versions of C++. Starting with C++ 11, developers have a new technique for solving these problems in ways that bring C++ code back to its concise roots.

You can solve a number of C++ development problems using lambda expressions, but the typical problem is one of making the code more concise and easier to read. There is absolutely nothing wrong with the Problem example shown — it works just fine as shown.

#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
class MyFunctor
{
public:
    void operator()(int x)
    {
        cout << x << endl;
    }
};
void ProcessVector(vector<int>& vect)
{
    MyFunctor Func;
    for_each(vect.begin(), vect.end(), Func);
}
int main()
{
    vector<int> MyVector;
    MyVector.push_back(1);
    MyVector.push_back(2);
    MyVector.push_back(3);
    MyVector.push_back(4);
    ProcessVector(MyVector);
}

In this case, the example creates a vector, MyVector, and populates it with data. It then calls ProcessVector() to perform a task with the data in the vector.

The call to ProcessVector() creates a functor — a special class of object that acts as if it’s a function — named Func. This is an extremely useful kind of a class. For now, all you need to know is that it’s a special kind of a class that acts like a function.

The for_each() algorithm is part of the standard library. It processes each element in vect, the vector passed to ProcessVector(), starting at the first element (defined by vect.begin()) and ending with the last element (defined by vect.end()) using Func.

When you look at MyFunctor, you see a definition for an operator that requires a single int input, x. All that the code does is output x to the console. So you see the following output from this example.

1
2
3
4