C++ 比较两个数组并将差异答案放入另一个数组
我有两个数组,需要比较它们。将C++ 比较两个数组并将差异答案放入另一个数组,c++,arrays,C++,Arrays,我有两个数组,需要比较它们。将P[P]中的每个元素和child1[q]中的每个元素进行比较。如果不匹配,则P[P]中的元素将存储在另一个新数组中。我应该在哪里保存cout语句,以便将不匹配的数字放入另一个数组 多谢各位 int P[ ]={3,7,6,5,2,4,1,8}; int child1[ ]={3,7,6,5,8,6,7,2}; // getting the missing numbers for(int p=0;p< r;p++) // here r is size of
P[P]
中的每个元素和child1[q]
中的每个元素进行比较。如果不匹配,则P[P]
中的元素将存储在另一个新数组中。我应该在哪里保存cout
语句,以便将不匹配的数字放入另一个数组
多谢各位
int P[ ]={3,7,6,5,2,4,1,8};
int child1[ ]={3,7,6,5,8,6,7,2};
// getting the missing numbers
for(int p=0;p< r;p++) // here r is size of the array i.e.8
{
for (int q=0;q< r;q++)
{
if (child1[q]==P[p])
{
p++;
}
q++;
}
cout<< P[p]; // i have a problem here.where should i keep this statement for getting the mismatched number into an another array
int M[p]=P[p]; //the result must be M[2]={4,1}
}
intp[]={3,7,6,5,2,4,1,8};
int child1[]={3,7,6,5,8,6,7,2};
//找到丢失的号码
for(int p=0;p如果(child1[q]=p[p]);
我所看到的是,您正试图将值从p[p]
分配给child1[q]
。没有比较,而且p
每次都会更改,因为没有代码与关联,如果
检查下面的代码
if (child1[q]==P[p])
{
p++;
}
试着这样做:
int i=0;
if (child1[q]!=P[p]);
{
cout<< P[p]; //<===Your cout statment goes here
M[i++]=P[p];
}
else
{
//do your increament
}
inti=0;
如果(child1[q]!=P[P]);
{
cout如果您尝试这样的交叉检查:
P= 1 2 3
child1=4 5 6
Checking= (1,4),(1,5),(1,6),(2,4),(2,5),(2,6),....
P= 1 2 3
Child1= 4 5 6
Checking= (1,4),(2,5),(3,6)
试试这个:
int i=0;
for(int p=0;p<r;p++)
{
for(int q=0;q<r;q++)
{
if (child1[q]!=P[p]) //Mismatch
{
cout<< P[p]; //Printing mismatched value
M[i]=P[p]; //Assigned to another array called M[]
i++; //Increments index of array M[]
}
}
}
这样就不必对循环使用2
int i=0;
for(int p=0;p<r;p++)
{
if (child1[p]!=P[p]) //Mismatch
{
cout<< P[p]; //Printing mismatched value
M[i]=P[p]; //Assigned to another array called M[]
i++; //Increments index of array M[]
}
}
inti=0;
对于(int p=0;pif(child1[q]=p[p])
是赋值的,不是比较的,在if
语句之后有。对于循环,你不需要2,你只需要使用1。这听起来像是集合交集的倒数,不是吗?(换句话说,(a U b)\(a^b)
(^
是我为集合交集找到的最好的运算符:))需要反转比较。让我来修复它。谢谢你,但这次我得到了2 4 1 8..实际结果是4 1。即M={4,1}。每个元素应该与另一个数组中的每个元素进行比较感谢uthank u。我想要示例中描述的第一种方法u,但我得到了2 4 1 8。实际结果是4 1。即M={4,1}。每个元素应该与另一个数组中的每个元素进行比较感谢uP[]={3,7,6,5,2,4,1,8};
和int child1[]={3,7,6,5,8,6,7,2};
。实际结果是4,1
?如何?谢谢你P[]中的元素应与child1[]中的每个元素进行比较。P[5]即,P[]中的元素4与child1[]中的所有值进行比较。谢谢你
int P[]={3,7,6,5,2,4,1,8};
int child1[]={3,7,6,5,8,6,7,2};
std::vector<int> M;
for(int p=0; p < r; p++)
{
bool found = false;
for(int q=0; q < r; q++ )
{
if (child1[q]==P[p]);
{
found = true;
break;
}
}
if ( false == found )
{
cout<< P[p];
M.push_back(P[p]);
}
}
int P[]={3,7,6,5,2,4,1,8};
int child1[]={3,7,6,5,8,6,7,2};
int M[8];
int mCounter = 0;
for(int p=0; p < r; p++)
{
bool found = false;
for(int q=0; q < r; q++ )
{
if (child1[q]==P[p]);
{
found = true;
break;
}
}
if ( false == found )
{
cout<< P[p];
M[mCounter++] = P[p];
}
}