Remembering a function with two inputs in C ++

I have a function f (a, b) that accepts two inputs. I do not know in advance which values ​​a and b will be used. I'm fine, being a little wasteful from memory (I care about speed). I want to check if the output f (a, b) has already been delivered, and if so, to deliver this output again without restarting the process f (a, b).

It is trivially easy to do in Python with decorators, but C ++ is above my head.

+3
source share
4 answers

I would use std :: map (or perhaps std::unordered_map) whose key is std :: pair , or perhaps use a map of maps.

++ 11, , . , , Boost.

+6

:

, , f (a, b) , , f (a, b).

++, std::map. , , , std::pair .

#include <map>
#include <iostream>

uint64_t real_f(int a, int b) {
  std::cout << "*";
  // Do something tough:
  return (uint64_t)a*b;
}

uint64_t memo_f(int a, int b) {
  typedef std::pair<int, int> key;
  typedef std::map<key, uint64_t> map;
  static map m;
  key k(a,b);
  map::iterator it = m.find(k);
  if(it == m.end()) {
    return m[k] = real_f(a, b);
  }
  return it->second;
}

int main () {
  std::cout << memo_f(1, 2) << "\n";
  std::cout << memo_f(3, 4) << "\n";
  std::cout << memo_f(1, 2) << "\n";
  std::cout << memo_f(3, 4) << "\n";
  std::cout << memo_f(5, 6) << "\n";
}

:

*2
*12
2
12
*30

.

+3

++ 11 . f :

int f(int a, int b)
{
    // Do hard work.
}

, . :

template <typename F>
std::future<typename std::result_of<F()>::type>
schedule(F f)
{
    typedef typename std::result_of<F()>::type result_type;
    std::packaged_task<result_type> task(f);
    auto future = task.get_future();

    tasks_.push_back(std::move(task)); // Queue the task, execute later.
    return std::move(future);
}

:

auto future = schedule(std::bind(&f, 42, 43)); // Via std::bind.
auto future = schedule([&] { f(42, 43); });    // Lambda alternative.

if (future.has_value())
{
    auto x = future.get();  // Blocks if the result of f(a,b) is not yet availble.
    g(x);
}

: /, .

+1

f (a, b) - .

128 , - - :

  • ? ?
  • ? , ?
  • ? , ?

(a,b, f(a,b)) . , ,

  • window-slide it ( ):
  • (a,b,f(a,b),count) -
  • ( )
  • Google

You may also need to recalculate using the search engine if the latter is becoming more complex: std::mapand freinds do not appear for free, even if they are high-quality implementations.

0
source

All Articles