【问题标题】:c++ pass dynamically allocated 2d vector to functionc ++将动态分配的二维向量传递给函数
【发布时间】: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&lt;char&gt;*,但您发送的是 vector&lt;vector&lt;char&gt;&gt;。解决方案将取决于您希望solve_point 做什么。
  • 但一般情况下,使用&amp;进行引用传递。如果nullptr 是您传入的对象的可能值,您只需使用* 传递“引用”。
  • solve_point()的参数改为vector&lt;vector&lt;char&gt; &gt; &amp;board
  • 另一个问题的答案之一已经准确地说明了如何为vector&lt;vector&lt;char&gt;&gt; 声明solve_point。您至少需要解释为什么该答案还不够,否则您将再次得到相同的答案。放慢速度,仔细阅读类型、错误消息以及答案

标签: c++ pointers vector reference 2d-vector


【解决方案1】:

函数参数需要一个指向char 类型向量的指针,而调用函数传递的是vector&lt;char&gt; 类型向量。您是否正在寻找您的功能的以下变化?

//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]);
}

【讨论】:

    猜你喜欢
    • 2011-03-25
    • 2016-08-11
    • 1970-01-01
    • 1970-01-01
    • 2011-08-16
    • 2011-05-24
    • 2013-07-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多