【发布时间】:2020-06-29 21:28:57
【问题描述】:
我正在尝试通过 C++ 中的引用将动态分配的 2d 向量传递给函数。
最初我尝试使用 2d 数组来执行此操作,但有人告诉我尝试使用 2d 向量。由于转换错误,我下面的代码在 solve_point(boardExVector) 行失败。
#include <stdio.h> /* printf */
#include <bits/stdc++.h> /* vector of strings */
using namespace std;
void solve_point(vector<char> *board){
printf("solve_point\n");
board[2][2] = 'c';
}
int main(){
//dynamically allocate width and height
int width = 7;
int height = 9;
//create 2d vector
vector<vector<char>> boardExVector(width, vector<char>(height));
boardExVector[1][2] = 'k';
//pass to function by reference
solve_point(boardExVector);
//err: no suitable conversion function from "std::vector<std::vector<char, std::allocator<char>>, std::allocator<std::vector<char, std::allocator<char>>>>" to "std::vector<char, std::allocator<char>> *" exists
printf("board[2][2] = %c\n", boardExVector[2][2]);
}
我刚刚回到 c++,所以指针和引用是我正在努力提高的东西,我已经在网上寻找解决方案,并且已经尝试了一些通常涉及更改 solve_point 函数头以包含的解决方案* 或 & 但我还没有让它工作。任何帮助表示赞赏。谢谢
【问题讨论】:
-
solve_point需要vector<char>*,但您发送的是vector<vector<char>>。解决方案将取决于您希望solve_point做什么。 -
但一般情况下,使用
&进行引用传递。如果nullptr是您传入的对象的可能值,您只需使用*传递“引用”。 -
将
solve_point()的参数改为vector<vector<char> > &board。 -
另一个问题的答案之一已经准确地说明了如何为
vector<vector<char>>声明solve_point。您至少需要解释为什么该答案还不够,否则您将再次得到相同的答案。放慢速度,仔细阅读类型、错误消息以及答案。
标签: c++ pointers vector reference 2d-vector