2014-12-01 44 views
-3

所有值我有一個數組:檢查數組

int data[5] = {0,1,0,0,0}; 

我想檢查的data所有元素都是10。我嘗試了for loop,但沒有解決。

int control = 0; 
for(a=0; a<5; a++){ 
    if(data[a] == 1) control = 1;   
} 

可能嗎?謝謝。 (我很新的C)

+0

(谷歌)(http://stackoverflow.com/questions/14120346/c-fastest-method-to-check-if-all-array-elements-are-equal)。 – Maroun 2014-12-01 19:45:46

+0

如果一個元素不符合條件,請打破循環 – 2014-12-01 19:47:58

+2

@Lazy您想要完全檢查的是:所有元素是否爲1或所有元素是否爲0或所有元素是1還是0? – 2014-12-01 19:56:16

回答

1

你可以使用std::all_ofstd::any_of

#include <algorithm> 
int data[5] = {0,1,0,0,0}; 

if (std::all_of(std::begin(data), std::end(data), [](int i){return i == 0;})) 
{ 
    std::cout << "All values are zero"; 
} 

if (std::all_of(std::begin(data), std::end(data), [](int i){return i == 1;})) 
{ 
    std::cout << "All values are one"; 
} 

的好處是,這些功能展示short-circuiting行爲,所以他們不(一定)必須檢查每一個元素。

+1

std :: begin(data)and std :: end(data) - C++ 11 – 2014-12-01 19:49:38

+1

我是否缺少某些東西或者不是'開始「和」結束「缺少適當的範圍? – thokra 2014-12-01 19:52:30

+0

我的錯誤['begin'](http://en.cppreference.com/w/cpp/iterator/begin)和['end'](http://en.cppreference.com/w/cpp/iterator/end)確實有'std'前綴。 – CoryKramer 2014-12-01 19:58:57

0

使用一個布爾每個值:

bool one_found = false; 
bool zero_found = false; 

然後在循環檢查:

if (arr[i]) one_found = true; 
else zero_found = true; 
if (one_found && zero_found) break; 

如果只有一個在端部是真實的,各自的條件成立。

0

試試這個: -

int control = 0; 
for(a=0; a<5; a++) 
{ 
    if(data[a] == 1 || data[a]==0) 
    control++; 
} 
if (control == 5) 
{ 
    cout<<"The array only contains 1 and 0"; 
} 
else 
{ 
    cout<<"The array contains elements other than 0's and 1's"; 
} 
+0

你可能想在輸出之前添加一個條件來檢查控件是否與數組長度相同。這樣你就可以知道它的數組是全零還是全1。從那裏你需要一個機制來確定控制代表什麼。它全部是零還是全部? – Wilson 2014-12-01 20:10:27

+0

完成了,我以爲他會自己做。問題是要找出數組是否包含除0和1以外的任何元素,而且我認爲我做對了。 :-) – 3Demon 2014-12-01 20:16:21

1

而C版:OP說我要檢查,如果數據的所有元素都是1或0

int data[5] = {0,1,0,0,0}; 
int a, zeros=0, ones=0; 
for (a=0; a<5; a++) { 
    if (data[a] == 0) zeros++; 
    if (data[a] == 1) ones++; 
} 
if (zeros == 5) 
    printf ("All elements are 0\n"); 
else if (ones == 5) 
    printf ("All elements are 1\n"); 
else if (ones+zeros == 5) 
    printf ("All elements are 1 or 0\n"); 
else 
    printf ("Some elements are not 1 or 0\n"); 
+0

4個零和1個呢? – 2014-12-01 20:51:17

+0

謝謝@DieterLücking我已經改進了答案。 – 2014-12-01 22:23:11

0

你可以做到這一點一個for循環。你只需要一些跟蹤結果的方法。你可以有兩個代表真或假的變量。如果您從數組全部爲零或全爲零的假設開始,則可以將標誌設置爲true。然後在for循環中,如果您發現矛盾,則將相應的標誌設置爲false。在這種情況下,我只使用int 0作爲FALSE,使用int 1作爲TRUE;

int data[5] = {0,0,0,0,0}; 
int all_zero = 1; 
int all_ones = 1; 

for(i = 0; i < 5; i++){ 
    if(data[i] == 1){ 
     all_zero = 0; 
    } 
    else{ 
     all_ones = 0;