Compare 2 elements from two arrays in C ++

I have two arrays, each array has some values, for example:

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

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

How can i do this?

+4
source share
4 answers

If the arrays are so small, I would just take a brute force approach and skip 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 are going to deal with large arrays, you can, however, consider a better algorithm, since it is O (n ^ 2).

If, for example, one of your arrays is sorted, you can check for matches faster, especially as the length of the array increases. I would not worry about anything more complicated, though, if your arrays will always always contain several elements.

+7
source

Assuming both arrays are sorted, you can execute 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 when sorting them.

+3
source

The solution for sorted arrays has already been published. If the arrays are not sorted, you can build a set (for example, std::set or a hash set) from each and see if the sets intersect. You will probably have to store value pairs in sets to figure out which index was duplicated (and overload the comparison operators accordingly). This can lead to O (n log n) complexity.

+2
source
 //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 
0
source

Source: https://habr.com/ru/post/1314355/


All Articles