0

我正在尝试通过 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 函数头以包含 * 或&但我还没有让它工作。任何帮助表示赞赏。谢谢

4

1 回答 1

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]);
}
于 2020-03-18T19:07:57.790 回答