2017-08-27 105 views
1

對不起,我一直在做Python和JS,現在回到C++來分配一個數組。簡單的C++數組賦值

怎樣纔可以比這更容易做:

float* d1 = (float*)calloc(4,sizeof(float)); 
d1[0] = 1; 
d1[1] = 2; 
d1[2] = 3; 
d1[3] = 4; 

我習慣d1 = [1,2,3,4],不能換我圍​​繞它的頭......

+3

':: std :: array d1 {1.0f,2.0f,3.0f,4.0f};' – VTT

+4

[你幾乎沒有理由在C++中使用'malloc'函數族](https:/ /stackoverflow.com/questions/44588345/malloc-vs-new-for-primitives/44588567#44588567)。所以不要。 – StoryTeller

回答

1

試試這個代碼了:

float array[] = {1.0f,2.0f,3.0f,4.0f}; 

此代碼創建一個由4個元素組成的簡單數組。初始化時,陣列是以下內容:1,2,3,4。希望這可以幫助 。

0

如果數值在編譯時已知

float d1[4] = {1.0f, 2.0f, 3.0f, 4.0f}; 

std::array<float, 4> d1 {1.0f, 2.0f, 3.0f, 4.0f}; // since C++11 

是,在運行時生成的簡單的方式假設值,

std::array<float, 4> d1;      // or float d1[4] 
for (int i = 0; i < 4; ++i) d1[i] = i+1.0f; 

// or, instead of the loop, since C++11 

std::iota(std::begin(d1), std::end(d1), 1.0f); // iota() specified in <numeric> 

或(如果直到運行時才知道元素的數量)

std::vector<float> d1(number); 
for (int i = 0; i < number; ++i) d1[i] = i+1.0f; 

// or, instead of the loop, since C++11 

std::iota(d1.begin(), d1.end(), 1.0f); 
5

我看到以下選項用於創建float s的數組。

選項1

使用的規則陣列。

float d1[] = {1.0f, 2.0f, 3.0f, 4.0f}; 

float d1[4] = {1.0f, 2.0f, 3.0f, 4.0f}; 

選項2

使用std::array

std::array<float, 4> d1{1.0f, 2.0f, 3.0f, 4.0f} 

選項3

使用std::vector

​​

除非有強有力的理由,更喜歡使用std::arraystd::vector。如果您在編譯時知道數組的大小,則可以使用std::array。如果在編譯時不知道數組的大小,那麼std::vector是合適的。

使用std::arraystd::vector的主要好處之一是,您可以在函數調用中使用變量時找出數組的大小。如果使用常規數組,則數組衰減爲指針。您必須在另一個參數中傳遞大小以幫助該函數阻止使用超出邊界索引訪問數組。