C ++ - 选举通过功能的二维数组 [英] C++ - Returning a 2D array through function

查看:151
本文介绍了C ++ - 选举通过功能的二维数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我四处看了看,试图找出我是否应该返回C ++中的二维数组,但得到的答案混合

I've looked around trying to figure out if I should return a 2D array in C++, but got mixed answers.

有些答案说的没有的,因为数据是本地的功能,当它返回时,阵列指向垃圾数据(因为它可以在任何时间被覆盖)。然而,有的说的是的,返回它像一个正常的数组。

Some of the answers say no because the data is local to the function and when it returns, the array points to "junk data" (as it can be overwritten at any time). However, some said "yes, return it like a normal array."

所以,我的困境:

我有一个二维数组保存指针瓷砖对象

I have a 2D array that holds pointers to Tile objects

瓷砖*地图[128] [128];

我应该返回一个函数的阵列?为什么或者为什么不?如果答案是肯定的,我会怎么做呢?

Should I return the array in a function? Why or why not? If the answer is yes, how would I do that?

编辑:我不清楚​​。我想使一个消气方法返回地图变量,并能使用该指针阵列中的另一种功能。

I was unclear. I want to make a getter method to return the map variable and be able to use the pointers in the array in another function.

推荐答案

您可以这样做......问题是,你的来电者现在负责释放内存。他可能不知道你是怎么分配的。他应该调用free()?删除[]?操作系统提供一个免费的程序?或者通过一些其他的内存缓存系统在你的应用程序提供一个?

You could do that... the problem is that your caller is now responsible for freeing the memory. And he might not know how you allocated it. Should he call free()? delete[]? A free routine provided by the OS? Or one provided by some other memory caching system in your app?

解决此两种常用方法是:

Two common ways around this are:


  • 让来电者分配内存和你的函数只是填充它

  • 使用一个C ++数组类;这里,你可能有一个包含瓷砖的一个std ::向量*一个std ::向量。这是伟大的,因为它免除你的内存分配/释放手动处理。

但后来......谁去释放瓷砖*实例?以怎样的API?因此,也许你需要瓷砖矢量,而不是瓷砖的向量*。

But then... who's going to free the Tile* instances? And with what API? So perhaps you need a vector of vectors of Tile, rather than Tile*.

vector<vector<Tile>> map;

这篇关于C ++ - 选举通过功能的二维数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆