【发布时间】:2015-10-12 18:10:22
【问题描述】:
要获取c++ 中数组的位置,您可以执行以下操作:
class Slot
{
public:
int Color;
std::string name;
/*.... more properties*/
};
int main()
{
Slot pix[60];
Slot& randomSlot = pix[12];
randomSlot.Color = 12;
randomSlot.name = "sdsd";
Slot* addressOfSlot = &randomSlot;
Slot* arrayStart = pix;
//get the original pos
int x = addressOfSlot - arrayStart;
}
-
您将如何获得像这样的
2d array的 x 和 y 位置? :Slot pix[60][21];
我想使用这种方法,因为我将使用指针/引用,并且我希望有一种快速的方法来获得原始位置,
- 您也可以在 c# 中使用不安全代码或类似的代码来执行此操作吗?
【问题讨论】:
-
你将如何表示 [30][30]?您是否试图获得 2d 位置的 1d 位置?
-
你是说给定一个值,你想在数组中找到它的索引吗?
-
@NathanOliver 与它在 C#
byte[,] myArray中的表示方式相同,我确定在 c# 中是连续内存,我希望在 c# 中执行此操作,但 c++ 是解释问题的唯一方法。 Two-dimensional array in memory -
@RonBeyer 是正确的。
-
至少在 C# 中,鉴于您需要 O(1) 查找,更好的数据结构将是哈希表或字典。如果 X/Y 很重要,您可以将其与值一起存储为元组。