C 将一个数组的元素与另一个数组的所有元素进行比较
我想将一个数组的每个元素与另一个数组的所有元素进行比较。我想要实现的是,如果一个元素存在于另一个数组中,result=0,否则result=1C 将一个数组的元素与另一个数组的所有元素进行比较,c,C,我想将一个数组的每个元素与另一个数组的所有元素进行比较。我想要实现的是,如果一个元素存在于另一个数组中,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
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
}
}
}
intm,n;
对于(int i=0;i稍微调整代码(用实际使用的任何数据类型替换char
):
然后使用它
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
}
}
chara[50];
charb[50];
for(int i=0;i数组在哪里?不清楚您真正想要做什么。您是希望您的“任务”对每个可能的元素组合运行一次,还是希望您的一个任务或另一个任务仅在整个数组中有匹配的元素或没有匹配的元素时运行?换句话说,如果您有两个看起来像{1,2,3}的数组
和{4,5,6}
,您希望“不匹配”任务运行一次还是九次?我希望“不匹配”只运行一次。谢谢Hanks jonathon。您能给我解释一下为什么使用char更好吗?我打算使用带有整数元素的数组,再加上我必须处理数千个元素。然后使用int。这只是一个例子。
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
}
}