我正在尝试通过引用发送 2d 矢量,但似乎它不适用于几乎相同的方法

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";
}

这两种将二维向量作为参数传递的方法有什么区别??

您正在调用函数 minPathSum 使用花括号初始化列表创建类型 std::vector<vector<int>> 的临时对象。

因此编译器会发出一条错误消息,表明您正在尝试将临时对象与非常量左值引用绑定。

只需用限定符声明函数参数const

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