简体   繁体   中英

Compare 2 elements of two arrays in C++

I have two arrays each array has some values for instance:

int a[] =  {1, 2, 3, 4};
int b[] =  {0, 1, 5, 6};

now I need to compare the elements of the array (a) with elements in array (b).. if is there any match the program should return an error or print "error there is a duplicate value" etc.. in the above situation, it should return an error coz a[0] = b[1] because both are have same values.

How can I do this??

If the arrays are this small, I would just do a brute force approach, and loop through both arrays:

for (int i=0;i<4;++i)
{
    for (int j=0;j<4;++j)
    {
        if (a[i] == b[j])
        {
            // Return an error, or print "error there is a duplicate value" etc
        }
    }
}

If you're going to be dealing with large arrays, you may want to consider a better algorithm, however, as this is O(n^2).

If, for example, one of your arrays is sorted, you could check for matches much more quickly, especially as the length of the array(s) gets larger. I wouldn't bother with anything more elaborate, though, if your arrays are always going to always be a few elements in length.

Assuming both arrays are sorted, you can step them though them like this:

// int array1[FIRSTSIZE];
// int array2[SECONDSIZE];
for(int i=0, j=0; i < FIRSTSIZE && j < SECONDSIZE; ){
    if(array1[i] == array2[j]){
        cout << "DUPLICATE AT POSITION " << i << "," << j << endl;
        i++;
        j++;
    }
    else if(array1[i] < array2[j]){
        i++;
    }
    else{
        j++;
    }
}

This should have linear complexity, but it only works if they're sorted.

The solution for sorted arrays has already been posted. If the arrays are not sorted, you can build a set (eg std::set or a hash set) out of each and see if the sets are disjoint. You probably have to store value–index pairs in the sets to find out which index was duplicate (and overload the comparison operators appropriately). This might give O( n log n ) complexity.

//v={1,2,3,4};  vector
//v1={1,2,3,4}  vector

  bool f=0;
    if(equal(v.begin(),v.end(),v1.begin()))  //compare two vector, if equal return true
    {
        f=1;
    }

    }
    if(f==1)
        cout<<"Yes"<<endl;
    else cout<<"No"<<endl;

        enter code here

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM