Search code examples
c++constantsc++17pass-by-referencefunction-declaration

i am trying to send a 2d vector by reference but seems like its not working for pretty much same approach


    64.minimum-path-sum.cpp: In function ‘int main()’:
    64.minimum-path-sum.cpp:67:23: error: cannot bind non-const lvalue reference of type ‘std::vector<std::vector<int> >&’ to an rvalue of type ‘std::vector<std::vector<int> >’
       67 |         if(minPathSum(vector<vector<int>> {{1 , 2, 3}}) == 12)cout << "ACC\n";
          |                       ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    64.minimum-path-sum.cpp:57:46: note:   initializing argument 1 of ‘int minPathSum(std::vector<std::vector<int> >&)’
       57 |         int minPathSum(vector<vector<int>> & grid) {
          |    

                    ~~~~~~~~~~~~~~~~~~~~~~^~~~




#include<bits/stdc++.h>
#include "stringTo2dVector.h"
using namespace std;

 
int main(){

vector<vector<int>> c{{1 , 2, 3}};
if(minPathSum(c) == 12)cout << "ACC\n"; //No ERROR
else cout << "WA\n";

if(minPathSum(vector<vector<int>> {{1 , 2, 3}}) == 12)cout << "ACC\n"; // ERROR
else cout << "WA\n";
}

What is the difference between these 2 approach of passing a 2d vector as argument ??


Solution

  • You are calling the function minPathSum creating a temporary object of the type std::vector<vector<int>> using a braced init list.

    So the compiler issues an error message that you are trying to bind a temporary object with a non-coonstant lvalue reference.

    Just declare the function parameter with the qualifier const

    int minPathSum( const vector<vector<int>> & grid);