Is there any way to assign default value to a map passed as a parameter by reference to a function in C++?

I'm trying to use map in my recursive functions (as an implementation of DP). Here, I wrote a simple Fibonacci function (I know I can use a normal array here but I want to get some idea which I can use in other functions which will take more complex inputs like pairs, strings, objects etc).

#include <bits/stdc++.h>
using namespace std;
#define int long long

int fib(int n, map<int, int> &memo); // What I did

/* What I want:
Instead of pulling an external map as an argument,
the function will automatically create an empty map as a default parameter at the first call
and pass it by reference in the recursive calls. */

/* I tried some stuff
int fib(int n, map<int,int> memo={}); // Slow
int fib(int n, map<int, int> &memo, bool reset);  // Works, but I want to know if there are any better idea which doesn't take 3 inputs
int fib(int n, map<int, int> &memo={}); // Doesn't compile (my target is something close to this)
*/

signed main()
{
    map<int,int> mp; // Needs to be empty before being passed to fib()
    int n;
    cin >> n;
    cout << n << ' ' << fib(n, mp); // I want to use just fib(n)

    return 0;
}

int fib(int n, map<int, int> &memo) // The external memo needs to be empty
{
    if(n==!!n) return n;
    if(memo.find(n)!=memo.end()) return memo[n];

    if(n<0)
    {
        if(n%2) return fib(-n, memo);
        return -fib(-n, memo);
    }

    memo[n]=fib(n-1, memo)+fib(n-2, memo);
    return memo[n];
}

I want to know if there are any ways to implement the empty map parameter in C++.


Solution 1:

You can simply overload the function:

int fib(int n)
{
  std::map<int, int> map;

  fib(n, map);
}

int fib(int n, map<int, int> &memo) { ... }

Is this what you meant to achive?


Sidenote: You should remove #define int long long, it's not legal C++ and utterly confusing.