2014-03-03 74 views
0

我有两个数组,需要对它们进行比较。将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} 
} 
+0

'如果(child1 [Q] = P [P])'的分配,没有比较,在'if'语句后面有';'。 – fasked

+0

你不需要2'for'循环,你可以使用1. – user2485710

+0

这听起来像是集合交集的逆,不是吗? (换句话说,'(a U b)\(a^b)'('^'是我找到的最好的运算符:)) – Manu343726

回答

0

if (child1[q]=P[p]);

我看到你正试图从P[p]to child1[q] ..没有比较价值分配,也p会因为没有代码与if相关的每一次改变..

检查下面的代码..

if (child1[q]==P[p]) 
{ 
    p++; 
} 
0

试试这个方法:

int i=0; 

    if (child1[q]!=P[p]); 
    { 
     cout<< P[p]; //<===Your cout statment goes here  
     M[i++]=P[p]; 
     } 
    else 
    { 
    //do your increament 
    } 
0

如果你想这样的交叉检查:

P=  1 2 3 
child1=4 5 6 
Checking= (1,4),(1,5),(1,6),(2,4),(2,5),(2,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[] 
     } 
    } 
} 

OR

如果要检查哪些具有相同的位置值像这样:

P=  1 2 3 
Child1= 4 5 6 
Checking= (1,4),(2,5),(3,6) 

然后,您不必使用2 for循环。

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[] 
    } 
} 
+0

谢谢你想要第一种类型的方法吗?得到2 4 1 8。实际结果是4 1 .ie M = {4,1}。每个元素应该与另一个数组中的每个元素进行比较,谢谢 – user3363627

+0

'P [] = {3,7,6,5,2,4,1,8};'和'int child1 [] = {3,7, 6,5,8,6,7,2};'。实际结果是'4,1'?怎么样? –

+0

谢谢你应该将P []中的元素与child1 []中的每个元素进行比较。 P [5],即将P []中的元素4与child1 []中的所有值进行比较。谢谢你 – user3363627

0
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]); 
    } 
} 

如果你不想使用std::vector<int>M,您可以使用:

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]; 
    } 
} 
+0

比较需要颠倒。让我解决它。 –

+0

谢谢你,但我这次得到了2 4 1 8。实际结果是4 1 .i.e M = {4,1}。每个元素都应该与另一个数组中的每个元素进行比较,谢谢你 – user3363627

+0

@ user3363627我更新了代码。 –