2011-12-07 65 views
0

有沒有辦法做到這一點?這是我第一次使用數組和50個元素,我知道他們只會變得更大。將相同的值賦給數組中所有元素的方法

+1

按數組你是指'std :: vector'? – GWW

+4

請顯示一些代碼。目前我們不知道你的數組是什麼意思*它可能是'std :: vector','std :: array','char [50]'等等 – AJG85

回答

7

使用std::vector

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

+1,但是Matteo的答案比你的更好僅適用於初始化。 –

2

您可以使用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); 

如果要將所有元素設置爲的編號,你可以做這個快捷方式:

int array[50] = { }; 

或者,如果你在談論std::vector,還有就是採用向量的初始大小和哪些每個元素設置爲一個構造函數:

vector<int> v(50, n); // where "n" is the number to set all the elements to. 
9

無論使用什麼樣的數組,如果它提供迭代器/指針,則可以使用<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; 
+0

+1最佳答案,無論他使用什麼,甚至自定義數組類都可以實現迭代器,而'std :: fill'允許靈活地將值分配給元素範圍。 – AJG85

0
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 
} 
相關問題