Search code examples
javascriptc++unordered-mapmemoization

Default parameter in function to a reference in c++ unordered_map


I am a JS dev and to implement this function header,I do :

function gridTraveler(m,n,memo={})

Here,I know that the object would be passed by reference in JS.

So in C++,I decided to do:

int gridTraveler(int m,int n,std::unordered_map<int,int>& memo = {})

But I get an error : "initial reference to a non const must be an lvalue".

How should I pass the default parameter to the function as well as pass the hasmap by reference?

NOTE:I would be editing the memo object by adding in keys and value in the function body


Solution

  • What you meant can probably be achieved by a two-arg overload that takes care of the unordered map lifetime.

    int gridTraveler(int m,int n,std::unordered_map<int,int>& memo) {
        //your implementation here
    }
    
    int gridTraveler(int m, int n) {
        std::unordered_map<int,int> memo = {};
        return gridTraveler(m, n, memo);
    }