2014-12-01 39 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;