Hello. I trying to solve this problem. The user inputs 4 numbers to each array (they are 2). I must output the common elements. So this is the problem i'm stucking with .
Let's say
p = 1,2,2,3
p1 = 3,5,1,2

the output is 2 1 3 1 2

but it must be 2 1 3


How can i remove the duplicates?
here is the code

#include <iostream>
#include <cstdlib>
#include <conio.h>


using namespace std;
int main() 
{
int p[4] ,p1[4], num = 0 , p2[] = {};
cout<<"Enter 4 numbers of the first array ";
for(int a=0;a<4;a++){
	cin>>p[a];
}

system("CLS");
cout<<"Enter 4 numbers of the second array: ";
for(int a=0;a<4;a++){
	cin>>p1[a];
}

system("CLS");


for(int i = 0 ; i < 4; ++i) {
for (int j = 0 ; j < 4; ++j) {
	if(p[i]==p1[j]) {
		p2[num++] = p[j];
}
}
}

	cout<<"The number of common elements"<<num<<endl;
	cout<<"These are the common numbers: ";
	for (int k=0;k<num;k++){
		cout<<p2[k]<<" ";
	}
	getch();
	return 0;
	
}

Do you need to retain the original order? The standard library has a set_intersection() function that does what you want, but both sets need to be sorted:

#include <algorithm>
#include <iostream>
#include <iterator>

using namespace std;

template <typename T, int N>
int size(T(&)[N]) { return N; }

int main()
{
    int a[] = {1,2,2,3};
    int b[] = {3,5,1,2};
    
    sort(a, a + size(a));
    sort(b, b + size(b));
    
    set_intersection(a, a + size(a), b, b + size(b), ostream_iterator<int>(cout, " "));
    cout << '\n';
}

Without the ordering requirement, the linear intersection algorithm doesn't work. The naive non-ordered algorithm uses a more brute force (and thus less efficient) approach with nested loops:

for i = 0 to size(a)
    for j = 0 to size(b)
        if b[j] = a[i] and not contains(c, a[i])
            append(c, a[i])
        end if
    loop
loop

pff , so simple)) thank you a lot ;)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.