我正在尝试通过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 ++,所以我正在努力改进指针和引用,我在网上寻找了解决方案,并且已经尝试了一些方法,这些方法通常涉及更改resolve_point函数标头以包括*或&,但我还没有开始工作。任何帮助表示赞赏。谢谢
答案 0 :(得分:2)
函数参数需要一个指向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_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]);
}