# using arrays for set operators

• 07-19-2009
XodoX
using arrays for set operators
I want to use arrays to program a calculator that uses set operatiors. Like:

A= 1,2,3,4 B=1,2,3,4,5

A union B = 1,2,3,4,5

I'm asking the user for the input, but after that I'm stuck. I guess that I can use a loop that goes through the array and checks for dublicates and removes them. And then I can just display the output. I have no idea how to do this. Can anybody help me?
• 07-19-2009
Spidey
Well assuming your set is always in sorted order, here is a simple solution-

1 Create an array of the size of the largest set.

2 Loop through the array and check each element against the smallest set.
3 If the array doesn't contain the current element, add it to the array.
4 Continue from step 2 with the next largest set until you have reached the largest set.

If your elements are not in sorted order, you will just have to sort the new array.

Note that there are much more efficient ways of doing this.
• 07-19-2009
XodoX
Well, I don't know. What if it's not sorted?
• 07-19-2009
Spidey
Just use the same technique, and sort the array after your done with the union.
• 07-19-2009
XodoX
std::set which prevents you from adding duplicates could be used too, right?
• 07-19-2009
Spidey
Yes, std::set does not let you add duplicates to the set and keeps itself sorted.
I was assuming you had to use arrays, but if you can use set; all you have to do is

Go through all elements in all your arrays
And add them to the set.
This will make sure that your elements are unique and in sorted order.
• 07-20-2009
Sebastiani
>> I have no idea how to do this. Can anybody help me?

You could always use std::set_union. ;)
• 07-20-2009
iMalc
I would use assoc_vector from the Loki library - job done!
(or at least learn from it)