Evgenii Legotckoi
Aug. 21, 2019, 3:45 p.m.

C++14 - lambda function with cached return value

Content

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.


Code example

  1. #include <iostream>
  2. #include <string>
  3.  
  4. using namespace std;
  5.  
  6. int heavy_calc(int base) // heavy function that we want to call once
  7. {
  8. cout << "heavy_calc" << std::endl;
  9. // sleep(+100500 years)
  10. return base * 25;
  11. }
  12.  
  13. void calclulateValue(int base)
  14. {
  15. // The following construction allows you to cache the result of executing a heavy function for the duration of one call to calclulateValue
  16. auto foo
  17. {
  18. [cache = heavy_calc(base)]()
  19. {
  20. return cache;
  21. }
  22. };
  23. // We call the lambda twice with the cached heavy calc value
  24. // In this case, heavy calc is called only once
  25. int fooFoo = foo() + foo();
  26. cout << fooFoo << std::endl;
  27. }
  28.  
  29. int main()
  30. {
  31. // Call calclulateValue twice with a different base value,
  32.     // to show that the cache is reset every time calclulateValue is called
  33. calclulateValue(1);
  34. calclulateValue(10);
  35. return 0;
  36. }

Result

  1. heavy_calc
  2. 50
  3. heavy_calc
  4. 500

Do you like it? Share on social networks!

Comments

Only authorized users can post comments.
Please, Log in or Sign up
  • Last comments
  • Evgenii Legotckoi
    March 9, 2025, 9:02 p.m.
    К сожалению, я этого подсказать не могу, поскольку у меня нет необходимости в обходе блокировок и т.д. Поэтому я и не задавался решением этой проблемы. Ну выглядит так, что вам действитель…
  • VP
    March 9, 2025, 4:14 p.m.
    Здравствуйте! Я устанавливал Qt6 из исходников а также Qt Creator по отдельности. Все компоненты, связанные с разработкой для Android, установлены. Кроме одного... Когда пытаюсь скомпилиров…
  • ИМ
    Nov. 22, 2024, 9:51 p.m.
    Добрый вечер Евгений! Я сделал себе авторизацию аналогичную вашей, все работает, кроме возврата к предидущей странице. Редеректит всегда на главную, хотя в логах сервера вижу запросы на правильн…
  • Evgenii Legotckoi
    Oct. 31, 2024, 11:37 p.m.
    Добрый день. Да, можно. Либо через такие же плагины, либо с постобработкой через python библиотеку Beautiful Soup
  • A
    Oct. 19, 2024, 5:19 p.m.
    Подскажите как это запустить? Я не шарю в программировании и кодинге. Скачал и установаил Qt, но куча ошибок выдается и не запустить. А очень надо fb3 переконвертировать в html