我想将一个数组的每个元素与另一个数组的所有元素进行比较。我想要实现的是,如果一个元素存在于另一个数组中,result = 0,否则result = 1
int m,n;
for(int i=0; i<m; i++) {
for(int j=0; j<n; j++) {
if(i==j) {
result =0;
//perform a task
break;
}
if(i!=j) {
result = 1;
//perform another task
break
}
}
}
但是,我无法在第二个if()
中实现我想要的答案 0 :(得分:2)
稍微调整一下代码(用您实际使用的数据类型替换char
):
char A[50];
char B[50];
for(int i=0; i<50; i++) { // Iterate through A from 0 to 50
for(int j=0; j<50; j++) { // Iterate through B from 0 to 50
if(A[i] == B[j]) {
// Item from A exists in B
}
else {
// Item from A does not exist in B
}
}
}
请注意,“else
”代码将针对每个元素运行一次。
我们可以做得更好。首先创建一个搜索数组的实用程序函数:
bool item_exists(char item, char[] array, int array_len) {
for (int i=0; i<array_len; i++) {
if (array[i] == item)
return true;
}
return false;
}
然后使用它。
char A[50];
char B[50];
for(int i=0; i<50; i++) {
if (item_exists(A[i], B, 50)) {
// Item from A exists in B
}
else {
// Item from A does not exist in B
}
}