[英]Create an array of an array of structs?
這個問題是關於結構體數組的語法。
我有一個接受兩個整數的結構:
struct point
{
int x, y;
};
我創建了另一個結構,其中包含以下8種結構:
//Creating an Array of Array of structs
struct Arraypoint
{
point variable[8];
};
//Not sure if this is the correct way to do it.
現在,在main
,我想聲明一個具有8個索引的Arraypoint
類型的數組變量,因此有效地,我將擁有8 * 8 = 64
結構point
元素和128
整數( 64
x和64
y)。
另外,如何從數組Arraypoint
訪問單個元素結構點?
在main
聲明之后可以說Arraypoint是2。
Arraypoint arr[2];
如何初始化元素而不必鍵入arr[0].variable[0].x = ...
或不使用for循環。 為什么我不能執行以下操作,但它似乎不起作用。
Arraypoint arr[2] = { {(x,y),(x,y),(x,y),(x,y),(x,y),(x,y),(x,y),(x,y)},
{(x,y),(x,y),(x,y),(x,y),(x,y),(x,y),(x,y),(x,y)} }//xy are rand
我在代碼中使用了花括號,返回的錯誤是missing braces around initializer for type point
,而missing braces around initializer for type point
too many initializers for type Arraypoint
。
在C ++中,您只需編寫:
Arraypoint arr[8];
然后可以通過以下方式訪問單個點:
arr[i].variable[j];
不過,實際上,最好使用例如
std::vector<std::vector<point> >
或使用重載的operator(int i, int j)
編寫自己的類。 例如:
class PointMatrix
{
private:
std::vector<point> m_points;
public:
PointMatrix() : m_points(64) {}
point& operator()(int i, int j) { return m_points[8 * i + j]; }
const point& operator()(int i, int j) const { return m_points[8 * i + j]; }
};
PointMatrix mat;
m(3, 4).x = 23;
struct Arraypoint arraypoints[8];
我想,這就是你所追求的。 要使用它們:
int firstx = arraypoints[0].variable[0].x;
雖然不是很漂亮
struct point { int x, y; };
struct point[8][8] arraypoints;
可能更好嗎? 不知道你到底在追求什么。
要創建Arraypoints
數組,您可以執行以下操作:
Arraypoint arr[8];
要訪問元素:
arr[i]
將返回第i
個Arraypoint元素
arr[i].variable[j]
將返回元素中的第j
個點
arr[i].variable[j].x
將返回該點的x
坐標。
知道了: ideone.com/ix3hC 。 Arraypoint::variable
必須具有自己的{ }
對。
struct point
{
int x, y;
};
#define P {0, 0}
struct Arraypoint
{
point variable[8];
};
#define V { P, P, P, P, P, P, P, P}
#define AP { V } //this is the pair you missed
int main() {
Arraypoint arr[2] = { AP, AP };
}
所以我意識到了為什么不能這樣聲明我的數組,
Arraypoint arr[2] = { {(x,y),(x,y),(x,y),(x,y),(x,y),(x,y),(x,y),(x,y)},
{(x,y),(x,y),(x,y),(x,y),(x,y),(x,y),(x,y),(x,y)} }
//xy are randomn integer values
這是因為在我的Arraypoint的結構聲明中,它接受了8個類型為point的元素。 所以我必須創建指向store(x,y)的point類型的變量,然后才能將此變量存儲在Array point中。
point point1 = {x,y}, ...;
Arraypoint arr[2] = { {point1,point2,point3,point4,point5,....} };
只供將來遇到相同問題的人使用。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.