I'm trying to pass a dynamically allocated 2d vector to a function by reference in c++.
Originally I was trying to do this with a 2d array, but I was told to try with a 2d vector instead. My code below is failing at the solve_point(boardExVector) line due to a conversion error.
#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]);
}
I'm just getting back into c++ so pointers and references are something I'm working on getting better at, I've looked for solutions to this online and have tried some already which usually involve changing the solve_point function header to include a * or & but I haven't gotten it to work yet. Any help is appreciated. Thanks
The function argument expects a pointer to a vector of char
type, while the caller function is passing a vector of vector<char>
type. Are you looking for the following changes in your function?
//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]);
}