Advanced search

C++C ++ 17 - Lazy template functor with caching heavy function computation result

Aug. 22, 2019, 2:42 a.m.

C++17, lambda, auto, functor

Developing the idea of caching the result of calculations of heavy functions , I propose to write a small template class, which will take the function as an argument, namely the lambda function, as the most universal an instrument within which a heavy function will be performed.

In this case, the result of the function will not be calculated at the time of creation of the Functor, but at the time of calling the operator parentheses () . And at the same time, the result will be cached. That will allow not to call a heavy function more than once as part of the execution of a method.

C++C++14 - lambda function with cached return value

Aug. 21, 2019, 4:45 a.m.

lambda, auto, cache, C++14, C++

Suppose we wrote a function that calculates some value or uses a function to calculate this value, while the function_ which calculates the value is quite expensive to calculate and works for a long time. In this case, we call the lambda function several times in some code.

To avoid multiple calls to the heavy function, we can cache the value that the heavy function returns.

C++C++14 - unnamed structure as auto value returned by function

Aug. 21, 2019, 2:56 a.m.

C++, C++14, auto, lambda

Let's look at an interesting construction from the C++14 standard, which allows you to return the structure used in one place of the code, but you need to return an object with named fields.

Such a construction can serve as a replacement for std::tuple. At the same time, we will not need to declare any additional structures that we are not going to transfer anywhere, since we need to get only a set of data that we will somehow use immediately at the place of return and will not transfer further in the same form.

C++The idiom RAII and the principle of structured programming that a function must have one entry point and one exit point

Aug. 6, 2018, 1:52 a.m.

template, lambda, C++11

The world of programming in C ++ in the new standards allows us to get up a variety of things, thanks to which we can safely abandon some old statements or principles, or simply flexibly approach these principles.

I would like to outline my view on the work of the RAII idiom and the C ++ 11 standard with respect to one established principle whose authorship is attributed to Edsger Dijkstra :

"The module (in this case the function) must have only one entry point and only one exit point"

For this principle, multiple returns in a function / method are contrary to the principles of structured programming for the following reasons:

  • the complexity of debugging code with the use of multiple returns returns increases with the number of these same return, that is, you never know when the function or method of an object just exited.
    the complexity of code support, when all the points of the call are not visible at the initial look at the function. Also, it is not known whether the code added to the end of the function will execute or not, especially if the program logic should always execute this code. That is, in the case of multiple returns, you will have to implement this code before every call to the return operator.

But modern C ++ has already changed significantly since the times of Dijkstra and the means of the latest C ++ standards allow to bypass or significantly level out the influence of the reasons that caused the formulation of the principles of structured programming.

C++Cooking lambda functions in C ++ - Part 2 - Recursive lambda functions using the example of factorial calculation

In the previous article , we got acquainted with the structure of lambda functions, and now we'll play with lambdas, calculate the factorial, and consider how the lambda function can be applied for this.

Let's consider for the beginning the usual variant of factorial calculation, and also we will specify that such a recursive function.

Recursive function

A recursive function is that function that calls itself. This means that inside the function there is a call to itself, and infinite recursion can occur if the function code does not have the conditions for exiting recursion.

Here is an example of such an infinite recursive function, the program with which it terminates crash due to overflow of the call stack.

#include <iostream>

using namespace std;

void infiniteRecursiveFunction()
{
    cout << "Hello World!" << endl;
    infiniteRecursiveFunction();
}

int main()
{
    infiniteRecursiveFunction();
    return 0;
}

QtQt/C++ - Lesson 055. QSignalMapper VS lambda functions

QSignalMapper is a wonderful class to organize the work of the signals and slots dynamically created objects. For example, the dynamically created buttons or objects in QStackedWidget. This was particularly true in older versions of the software, that is, and relied on Qt 4.8, which signals and slots system was based on the use of macros. But in the current realities of the new syntax in the indexes is much more convenient, and also supports a lambda function that can afford and does get rid of the application QSignalMapper, which will look like a monstrous throwback to new projects that use the latest version of the framework Qt and C++ language standards.

And when you consider more and congestion map() and mapped(), then it does with QSignalMapper code even more terrible, if used to connect signals and slots with the use of pointers, since it is necessary to cast the signals and slots, but more on that later.

Therefore, let us consider a small project that will be based on the example of the official documentation of Qt. Namely, an example will next. We have QLabel, QPushButton and Vertical Layout . By pressing a button in the Vertical Layout will be added to other dynamic buttons, by clicking on which QLabel will display the text from the button number in the following form: "Button 2". In the following figure shows an example of the application whose appearance will not differ, while the software implementations of the code will be a few.

How to become an author?

Contribute to the evolution of the EVILEG community.

Learn how to become a site author.

Learn it
Donate

Good day, Dear Users!!!

I am Evgenii Legotckoi, developer of EVILEG. And it is my hobby project, which helps to learn programming another programmers and developers

If the site helped you, and you want also support the development of the site, than you can donate by following ways

PayPalYandex.Money
Timeweb

Let me recommend you the excellent hosting on which EVILEG is located.

For many years, Timeweb has been proving his stability.

For projects on Django I recommend VDS hosting

View Hosting Timeweb
g
May 29, 2020, 2:32 p.m.
glushchenkoin

C ++ - Test 004. Pointers, Arrays and Loops

  • Result:40points,
  • Rating points-8
AS
May 26, 2020, 11:29 a.m.
Artem Sun-Dun-Chan

C ++ - Test 004. Pointers, Arrays and Loops

  • Result:50points,
  • Rating points-4
MN
May 25, 2020, 11:33 a.m.
Mitja Nagibin

C ++ - Test 004. Pointers, Arrays and Loops

  • Result:50points,
  • Rating points-4
Last comments
May 29, 2020, 1 p.m.
Evgenij Legotskoj

Django - Tutorial 023. Like Dislike system using GenericForeignKey

Думал так, но похоже что нет. {{ post.votes.likes.user.username }} Это же QuerySet будет, а не отдельный единственный объект {% for vote in post.votes %} {{ vote.user.username …
May 29, 2020, 11:43 a.m.
Vladislav Melenchuk

Django - Tutorial 023. Like Dislike system using GenericForeignKey

А как получить имя пользователя, который поставил лайк? Думал так, но похоже что нет. {{ post.votes.likes.user.username }}
May 29, 2020, 6:30 a.m.
Evgenij Legotskoj

Qt/C++ - Lesson 039. How to paint stroke in QSqlTableModel by value in the column?

У меня работает. Исправлял в проекте, который приложен к статье. А что происходит в вашем коде, с учётом места вызова этого кода, я знать не могу ;) Дебажьте и добавляйте условия, кото…
MA
May 29, 2020, 6:27 a.m.
Mihail A

Qt/C++ - Lesson 039. How to paint stroke in QSqlTableModel by value in the column?

QModelIndexList rowIndexes = ui->tableView->selectionModel()->selectedRows(); model->removeRows(rowIndexes.first().row(), rowIndexes.size()); model-&…
May 29, 2020, 6:14 a.m.
Evgenij Legotskoj

Django - Tutorial 036. How to add authentication through social networks. VKontakte

Неправильно прописали URL, на который возвращается ответ от OAuth ВКонтакте. Настраивайте ваше приложение в консоли разработчика ВКонтакте
Now discuss on the forum
DK
May 29, 2020, 1:27 p.m.
Dzhon Kofi

QMap<> какой ключ лучше

это ясно. Вопрос в том, как быстро мапа будет отрабатывать, если ключом будет QModelIndex. Какой параметр индекса возьмет за ключ. И вот насколько это будет медленнее или быстрее, чем QString пр…
DK
May 29, 2020, 11:10 a.m.
Dzhon Kofi

QModelIndex становится не действительным, но валидный

Привет. Есть проблема с индексом и для меня это чистая магия: Сначала, что делаю: на вьюхе есть редактируемые ячейки. Пользователь редактирует одну, потом внезапно решает не сохраниться и ш…
May 29, 2020, 7:52 a.m.
Vladimir Sergeevich

Масштабирование двумя пальцами на мобильных платформах

Я планировал описать этот момент на блоге, но никак руки не доходят (уже год). Летом дойдут. Тем не менее, у меня в репозитории лежит рабочий код игрушки "пазлы", где есть все это. …
May 29, 2020, 6:51 a.m.
Evgenij Legotskoj

Графическое ускорение

Зависит от платформы и поддерживаемых технологий. В QML в первую очередь используется OpenGL и отрисовка производится средствами GPU. Но может переключаться на использование CPU и прог…
IP
May 29, 2020, 1:55 a.m.
Igor' Poroshin

QTablwView + QSqlQueryModel скрыть пустой столбец

Да, понятно. В данном случае лучше использовать серверную процедуру (если такие поддерживаются), в которой будет проверяться наличие всех пустых строк у нужного столбца и вызываться соответ…
About
Services
© EVILEG 2015-2020
Recommend hosting TIMEWEB