Home

Create More Readable and Concise C++ Code

|
Updated:  
2016-03-26 08:30:12
|
C++ For Dummies
Explore Book
Buy On Amazon

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

About This Article

This article is from the book: 

About the book author:

John Paul Mueller is a freelance author and technical editor. He has writing in his blood, having produced 100 books and more than 600 articles to date. The topics range from networking to home security and from database management to heads-down programming. John has provided technical services to both Data Based Advisor and Coast Compute magazines.

Jeff Cogswell has been an application developer and trainer for 18 years, working with clients from startups to Fortune 500 companies. He has developed courses on C++ and other technologies.