簡體   English   中英

為數組中的所有元素分配相同值的方法

[英]A method to assign the same value to all elements in an array

反正有這樣做嗎? 這是我第一次使用數組及其50個元素,我知道它們只會變得更大。

無論使用哪種數組,如果它提供迭代器/指針,都可以使用<algorithm>標頭中的std::fill算法。

// STL-like container:
std::fill(vect.begin(), vect.end(), value);

// C-style array:
std::fill(arr, arr+elementsCount, value);

(其中value是要分配的值, elementsCount是要修改的元素數)

並不是說手工實現這樣的循環會如此困難...

// Works for indexable containers
for(size_t i = 0; i<elementsCount; ++i)
    arr[i]=value;

使用std::vector

std::vector<int> vect(1000, 3); // initialize with 1000 elements set to the value 3.

如果必須使用數組,則可以使用for循環:

int array[50];

for (int i = 0; i < 50; ++i)
    array[i] = number; // where "number" is the number you want to set all the elements to

或作為快捷方式,使用std::fill

int array[50];

std::fill(array, array + 50, number);

如果要將所有元素設置為0 ,則可以執行以下快捷方式:

int array[50] = { };

或者,如果您在談論std::vector ,則有一個構造函數,該構造函數采用vector的初始大小以及將每個元素設置為以下內容的方式:

vector<int> v(50, n); // where "n" is the number to set all the elements to.
for(int i=0;i<sizeofarray;i++)
array[i]=valuetoassign

using method


void func_init_array(int arg[], int length) {
  for (int n=0; n<length; n++)
   arg[n]=notoassign
}

暫無
暫無

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

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