簡體   English   中英

我如何在C ++中獲得此結果? 指向數組的數組

[英]How can I achieve this result in c++? Arrays pointing to arrays

我正在嘗試使用c / c ++進行以下操作。 為了解釋代碼應如何工作,我編寫了此示例python代碼。

A=[1,2]
B=[3,4]
C=[5,6]

X=[A,B,C]

print(X[2][1]) ##this should print the second element of the third array (6)

當在python中創建一個先前創建的列表的列表時,就像定義一個二維數組(顯然無法按名稱調用每個子數組)一樣。

在c / c ++中,我無法執行此操作。 我在互聯網上讀到,當我指向數組時,我將始終得到第一個元素,這是真的嗎?

我可以用C ++創建一個二維數組,但是我需要先定義每個數組(A,B,C),然后在大數組X中列出所有這些數組。如何實現此任務?

這里:

int A[]={1,2};
int B[]={3,4};
int C[]={5,6};
int* X[]={A,B,C};
printf("%d\n",X[2][1]);

您也可以使用std :: vector來完成這項工作。

int A[]={1,2};
int B[]={3,4};
int C[]={5,6};
std::vector<int> a(A,A+1);
std::vector<int> b(B,B+1);
std::vector<int> c(C,C+1);
std::vector<std::vector<int> > x;
x.push_back(a); x.push_back(b); x.push_back(c);
printf("%d\n",x[2][1]);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM