Reputation: 1
I need to create a union array of two sets, given as C-arrays. This is what I have so far. I think my if condition is correct, but the output only print out one set of that array. Can you point out what I did wrong?
#include "union_intersection.h"
#include <iostream>
using namespace std;
template <typename T>
void Union(T* left, int left_size,
T* right, int right_size,
T* result, int& result_size)
{
int i=0, j=0;
while (i< left_size && j <right_size){
if (left < right)
{
result = left;
cout<< *result<< "\t";
i++;
left++;
result_size++;
}
else if (right<left)
{
result =right;
cout<< *result << "\t";
j++;
right++;
result_size++;
}
else
{
result =left;
cout<< *result <<"\t";
i++; j++;
left++;
right++;
result_size++;
}
}
}
Upvotes: 0
Views: 67
Reputation: 1
With @MikeCat help, below is my finish function. I also include the loop to print out the remaining element.
template <typename T>
void Union(T* left, int left_size, T* right,
int right_size, T* result, int& result_size)
{
int i=0, j=0;
while (i< left_size && j <right_size){
if (*left < *right || j >=right_size)
{
result = left;
cout<< *result<< "\t";
i++;
left++;
result_size++;
}
else if (*right<*left || i>= left_size)
{
result =right;
cout<< *result << "\t";
j++;
right++;
result_size++;
}
else
{
result =left;
cout<< *result <<"\t";
i++; j++;
left++;
right++;
result_size++;
}
}
while (i < left_size)
{
cout<< *left<< "\t";
left++;
++i;
result_size++;
}
while (j < right_size)
{
cout<< *right<< "\t";
++j;
right++;
result_size++;
}
}
Upvotes: 0
Reputation: 75062
while
requires that both array have some elements left.Try this:
#include "union_intersection.h"
#include <iostream>
using namespace std;
template <typename T>
void Union(T* left, int left_size, T* right,
int right_size, T* result, int& result_size)
{
int i=0, j=0;
while (i< left_size || j <right_size){ // change condition to "at least one array have unprocessed elements"
if (j >= right_size || *left < *right) // compare what is pointed at, and add condition "reached at end of one array"
{
result = left;
cout<< *result<< "\t";
i++;
left++;
result_size++;
}
else if (i >= left_size || *right<*left) // compare what is pointed at, and add condition "reached at end of one array"
{
result =right;
cout<< *result << "\t";
j++;
right++;
result_size++;
}
else
{
result =left;
cout<< *result <<"\t";
i++; j++;
left++;
right++;
result_size++;
}
}
}
Also it looks weird that the value of the argument result
is ignored and used as simple local variable, but I don't think this is invalid because the question only says about printing out and there are no specifications about what should be written or read to/from what is pointed at by result
.
Upvotes: 0