c++将动态分配的2d向量传递给函数



我正试图通过引用将一个动态分配的2d向量传递给c++中的一个函数。

最初我试图用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_pointn");
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] = %cn", boardExVector[2][2]);
}

我刚刚回到c++,所以指针和引用是我正在做得更好的事情,我已经在网上寻找了解决方案,并且已经尝试了一些,通常包括更改solve_point函数头以包含*或&但我还没开始工作。感谢您的帮助。感谢

函数参数需要指向char类型向量的指针,而调用方函数正在传递vector<char>类型向量。您是否希望在您的功能中进行以下更改?

//bits/stdc++.h is not a standard library and must not be included.
#include <iostream>
#include <vector> /* vector of strings */
using namespace std;
void solve_point(vector<vector <char>> &board){
printf("solve_pointn");
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] = %cn", boardExVector[2][2]);
}

最新更新