Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <unordered_map>
- class CachingCalculator
- {
- class Arguments
- {
- public:
- Arguments(int firstArgument, int secondArgument)
- {
- this->firstArgument = firstArgument;
- this->secondArgument = secondArgument;
- }
- bool operator==(const Arguments &other) const
- {
- return (firstArgument == other.firstArgument
- && secondArgument == other.secondArgument);
- }
- int firstArgument;
- int secondArgument;
- };
- public:
- class hash<Arguments>
- {
- public
- std::size_t operator()(const Arguments& k) const
- {
- using std::size_t;
- return (pow(k.firstargument,k.secondargument));
- }
- };
- CachingCalculator(int(*func)(int, int))
- {
- this->func = func;
- }
- ~CachingCalculator()
- {
- for (std::unordered_map<Arguments*, int>::iterator it = calculations.begin(); it != calculations.end(); ++it)
- {
- delete it->first;
- }
- }
- int calculate(int firstArgument, int secondArgument)
- {
- Arguments* args = new Arguments(firstArgument, secondArgument);
- std::unordered_map<Arguments*, int>::iterator it = calculations.find(args);
- if (it != calculations.end())
- return it->second;
- std::cout << "not found\n";
- int calculation = func(firstArgument, secondArgument);
- calculations[args] = calculation;
- return calculation;
- }
- private:
- std::unordered_map<Arguments*, int> calculations;
- int(*func)(int, int);
- };
- #ifndef RunTests
- int modulo(int a, int b)
- {
- std::cout << "Function modulo has been called.\n";
- return a % b;
- }
- int main()
- {
- CachingCalculator calculator(modulo);
- // Function modulo should be called.
- std::cout << calculator.calculate(5, 2) << '\n';
- // Function modulo should be called.
- std::cout << calculator.calculate(7, 4) << '\n';
- // Function modulo shouldn't be called because we have already made a call with arguments (5, 2)!
- // Instead, result should be pulled from the cache!
- std::cout << calculator.calculate(5, 2) << '\n';
- }
- #endif
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement