I was able to write a function that prints out the intersection of two arrays. However, I am trying to obtain the value of the members of the intersection.
If our final intersection is {6, 12}
I should return 2 as the value because I have 2 members. My return value is 1 and I don't know what I am doing wrong.
int main()
{
int data1[] = { 3, 6, 9, 12};
int data2[] = { 2, 4, 6, 8, 10, 12 };
int result[] = {};
size_t length1 = sizeof(data1)/sizeof(int);
size_t length2 = sizeof(data2)/sizeof(int);
size_t resultMax= 0;
int i =0;
int j =0;
while (i < length1 && j < length2)
{
if (data1[i] < data2[j])
{
i++;
}
else if (data2[j] < data1[i])
{
j++;
}
else if (data1[i] == data2[j])
{
result[i] = data1[i];
cout << "valor : " << result[i] << endl; // output is 6 and 12
i++;
j++;
resultMax = sizeof(result[i])/sizeof(int);
}
}
cout << "Final Size: "<< resultMax; //output is 0
return resultMax;
}
Use std::vector instead of array.
# include<iostream>
# include<vector>
using namespace std;
int main()
{
vector<int> data1 = { 3, 6, 9, 12}, data2 = { 2, 4, 6, 8, 10, 12 }, result;
int i = 0, j = 0, length1 = data1.size(), length2 = data2.size();
while (i < length1 && j < length2)
{
if (data1[i] < data2[j])
i++;
else if (data2[j] < data1[i])
j++;
else if (data1[i] == data2[j])
{
result.push_back(data1[i]);
cout << "valor : " << data1[i] << endl;
i++;
j++;
}
}
cout << "Final Size: "<< result.size();
return 0;
}
Use the algorithm library, specifically std::set_intersection .
The following is a slightly adapted example from the above linked cppreference page:
int main()
{
std::vector<int> v1{3, 6, 9, 12};
std::vector<int> v2{2, 4, 6, 8, 10, 12 };
std::sort(v1.begin(), v1.end());
std::sort(v2.begin(), v2.end());
std::vector<int> v_intersection;
std::set_intersection(v1.begin(), v1.end(),
v2.begin(), v2.end(),
std::back_inserter(v_intersection));
std::cout << "Final Size: "<< v_intersection.size();
}
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.