简体   繁体   English

有没有办法通过引用 C++ 中的 function 为作为参数传递的 map 分配默认值?

[英]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).我正在尝试在我的递归函数中使用 map(作为 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).在这里,我写了一个简单的斐波那契 function (我知道我可以在这里使用普通数组,但我想知道我可以在其他函数中使用它,这些函数将需要更复杂的输入,如对、字符串、对象等)。

#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++.我想知道是否有任何方法可以实现 C++ 中的空 map 参数。

You can simply overload the function:您可以简单地重载 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.旁注:您应该删除#define int long long ,这是不合法的 C++ 并且完全令人困惑。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM