c++ - 如何解决将未知大小的二维数组传递给函数的问题?

标签 c++ arrays pointers parameter-passing multidimensional-array

我有一个程序,其中对象数组的大小是在运行时确定的,因此它是动态分配的(二维数组,从文件中读取)。我还有一个将这些对象作为参数的函数。问题是如果函数参数是传递给函数的二维数组,则应确定第二维。但是,就我而言,事实并非如此。我的程序无法编译,因为原型(prototype)没有提到第 2 个维度。

这是我尝试过的:

//global variables
int residentCount=0;
int hospitalCount=0;
Resident** residents;
Hospital** hospitals;
bool readFromFiles(const string, const string, const int); //sizes are determined in here
void print(Hospital*[hospitalCount], Resident*[residentCount]); //declaration issue

我该如何解决这个问题?

最佳答案

您正在使用 C++ 编程,因此您应该:

  • 尽可能避免自行动态分配和处理内存管理
    • 利用具有自动存储期限的对象,遵循 RAII idiom
  • 避免使用 C 风格的数组,实际上避免编写一般情况下只能像 C++ 一样编译的 C 代码
    • 使用 C++ 提供的强大功能,尤其是那些捆绑在 STL 中的功能
  • 避免在局部变量足够时使用全局变量

它可能是这样的:

typedef std::vector<Resident> Residents;
typedef std::vector<Hospital> Hospitals;

// passing by const reference:
void print(const std::vector<Hospitals>&, const std::vector<Residents>&);

int main()
{
    std::vector<Hospitals> hospitals;
    std::vector<Residents> residents;
    ...
} // <-- lifetime of automatics declared within main ends here

请注意 hospitalsresidents将是具有自动存储持续时间的对象,可以以与 C 风格的二维数组类似的方式使用。当执行超出main的范围时,这些 vector 被破坏并且内存,它们的元素(包括它们的元素的元素)之前所在的位置被自动清理。

另请注意,我建议您通过 const 引用传递,即 const std::vector<Hospitals>& ,这会阻止创建传递对象的拷贝和 const关键字明确地告诉调用者:“尽管您通过引用传递此对象,但我不会更改它。”

关于c++ - 如何解决将未知大小的二维数组传递给函数的问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15574620/

相关文章:

php - 当我将空值视为这样的数组时,为什么 PHP 不会提示?

C - 应用于矩阵的函数指针。段错误

c - strcpy(char*,char a[]) 给出了错误的输出。 (逐字反转字符串)

c++ - 解决循环依赖

c++ - 无法使用自定义类创建 QList

JavaScript Array - 过滤掉与特定字符串不匹配的值

c++ - 带 vector 指针的链表

c# - 将字符串从 C++ 传递到 C#

c++ - 如何从折叠表达式中获取索引

Python 类型错误 : only integer scalar arrays can be converted to a scalar index