在C/C ++中使用多维数组是不好的做法吗? [英] Is it bad practice to use multi-dimensional arrays in C/C++?

查看:75
本文介绍了在C/C ++中使用多维数组是不好的做法吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有些程序员似乎猛烈憎恨他们,而另一些程序员似乎认为他们很好.我知道可以对多维数组执行的所有操作也可以对常规数组执行,因此它们在功能上是等效的.使用多维数组是不好的做法,还是没关系?

Some programmers seem to violently hate them, while others seem to think they're fine. I know that anything that can be done to a multi-dimensional array can also be done to a regular array, so they're functionally equivalent. Is it bad practice to use multi-dimensional arrays, or does it not matter?

推荐答案

是否需要将多维数据存储在事先知道尺寸的位置?如果是这样,请使用多维数组.

Do you need to store multi-dimensional data where you know the dimensions ahead of time? If so, use a multi-dimensional array.

如果您不提前知道尺寸(例如,您将不得不动态分配数组),那么您要么需要

If you don't know the dimensions ahead of time (i.e., you're going to have to dynamically allocate the array), then you either need to either

  • 使用索引算法分配一维数组并模拟n维数组,或者
  • 将指针数组分配给元素数组以获取实际的多维数组语义

这取决于特定的用例,但是根据经验,我几乎总是喜欢前者,因为前者会减少内存管理的麻烦并减少堆分配.两种方法的复杂性都随着维数的增加而增加,但我认为,由于间接层的额外级别,后一种方法的复杂度要快得多.

It depends on the specific use case, but as a rule of thumb, I almost always prefer the former because it makes for less memory management hassle and fewer heap allocations. The complexity for both approaches grows as the number of dimensions increases, but, in my opinion, it grows much faster for the latter approach due to the extra levels of indirection.

这篇关于在C/C ++中使用多维数组是不好的做法吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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