提问人:Mohammed Ashiqur Rahman 提问时间:12/19/2021 最后编辑:Vlad from MoscowMohammed Ashiqur Rahman 更新时间:1/24/2022 访问量:69
我正在尝试通过引用发送 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";
}
将 2d 向量作为参数传递的这两种方法有什么区别?
答:
2赞
Vlad from Moscow
12/19/2021
#1
您正在调用函数,使用带支撑的 init 列表创建该类型的临时对象。minPathSum
std::vector<vector<int>>
因此,编译器会发出一条错误消息,指出您正在尝试将临时对象与非常量左值引用绑定。
只需使用限定符声明函数参数const
int minPathSum( const vector<vector<int>> & grid);
评论
minPathSum
使用命名空间 std;
是一个坏习惯