簡體   English   中英

如何初始化vlaue元素並將其逐個分配給數組

[英]how to initialise and assign vlaue element by element to array dynamically

我想在C ++中按元素為動態數組元素分配值。 我使用下面的代碼分配值

int *missedlst;
for(int i=0;i<10;i++){
missedlst = new int;
missedlst[i] = i;
}

如果我打印這些值,則只能正確顯示最后一個值。 其余的值不是:程序顯示一些垃圾值。 請幫助我在循環中逐個元素地賦值。

您當前的代碼中,您分配了十個不同的“數組”,並且每次僅分配一個int ,但是您將寫入此單元素數組的第i個元素,而這導致了未定義的行為 (當i為零時除外)。

為了使當前代碼正常工作,您需要重寫例如

int* missedLst = new int[10];  // Create an array of ten integers
for (int i = 0; i < 10; ++i)
    missedLst[i] = i;  // Set the i'th element to the value of i

但是,我建議您改用std::vector ,然后有三種方法來聲明和初始化vector:

  1. 基本上與您現在所做的相同:

     std::vector<int> missedLst(10); // Declare a vector of ten integers for (int i = 0; i < 10; ++i) missedLst[i] = i; // Set the i'th element to the value of i 
  2. 動態創建每個元素:

     std::vector<int> missedLst; // Declare a vector of integers, size zero for (int i = 0; i < 10; ++i) missedLst.push_back(i); // Add the value of i at the end 
  3. 使用標准算法函數std::iota初始化向量:

     std::vector<int> missedLst(10); // Declare a vector of ten integers std::iota(std::begin(missedLst), std::end(missedLst), 0); 

您的代碼正在完全按照您說的去做

int *missedlst;          // New pointer
for(int i=0;i<10;i++){   // Loop 10 times
    missedlst = new int; // Change what the pointer points to
    missedlst[i] = i;    // This makes no sense, you don't have an array
}

您要創建一個新的整數數組,然后分配值。

int size = 10;                   // A size that is easily changed.
int* missedList = new int[size]; // New array of size size
for(int i = 0; i < size; ++i){   // loop size times
    missedList[i] = i;           // Assign the values
}

// Do stuff with your missedList

// Delete the object.
delete[] missedList;

暫無
暫無

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

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