C++ All-in-One For Dummies
Book image
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 Mueller has produced 114 books and more than 600 articles on topics ranging from functional programming techniques to working with Amazon Web Services (AWS). Luca Massaron, a Google Developer Expert (GDE),??interprets big data and transforms it into smart data through simple and effective data mining and machine learning techniques.

This article can be found in the category: