Re: Cartesian product
zfareed@umd.umich.edu wrote:
I have a program that creates two sets, one thru user interaction and
the other with the use of an array. Can anyone help with coding for
finding the cartesian product of the two sets; i.e a relation?
#include <iostream>
#include <set>
#include <algorithm>
using namespace std;
int main()
{
int arr[] = {1,3,5,7,9,11,13,15,17,19,21,23,25,27,29};
int arrSize = sizeof(arr) / sizeof(int);
set<int> A;
set<int> B(arr,arr+arrSize);
int num1=0;
int num2=0;
for(int x=0;x<20;x++)
{
cout << "Please enter an even integer less than 100:" << endl;
cin >> num1;
if(A.find(num1) != A.end())
cout << num1 << " has already been entered!"
<< endl;
else if((num1 % 2) != 0)
cout << "That is not an even number!" << endl;
else
A.insert(num1);
}
cout << endl;
cout << "Set A has " << A.size() << "elements." <<endl;
cout << "Set B has " << B.size() << "elements." << endl;
system("pause");
return 0;
}
I have included the code below I got from a site that suggests
creating a struct pair and defining an operator, but I do not
understand it.
struct Pair{
int i;
int j;
};
int operator==(const Pair& p1,const Pair& p2){
return p1.i==p2.i && p1.j==p2.j;
}
set<pair> result;
Consider using std::pair<int,int> instead. The advantage is that is comes
with a correctly defined operator== and operator< so that you can use it
with std::set<>, i.e.,
std::set< std::pair<int,int> >
will be a set of ordered pairs of integers. Just what the doctor ordered.
Best
Kai-Uwe Bux