Click here to Skip to main content
15,867,835 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have two vectors A,B and I want to merge them to a vector C but I want to preserve any duplicates in each vector while discarding duplicates between the two.

For example if I have A{1,2,3,4,2,5} and B{7,8,2,2,2,3,3} I want C to be {1,2,2,2,3,3,4,5,7,8}. It doesn't need to be sorted. A and B can be sorted vectors if it's required.

What I have tried:

set_difference and set_symmetric_difference
Posted
Updated 11-Dec-21 10:00am
Comments
Richard MacCutchan 11-Dec-21 10:35am    
If you start by eliminating the entries in A that exist in B then you end with C=(1,2,2,2,3,3,4,5,7,8). However if you start by eliminating B versus A then C=(1,2,2,3,4,5,7,8). So you first need to decide which numbers to keep when you find duplicates.
John Brg 11-Dec-21 10:43am    
I shouldn't have to decide which numbers to keep. If the duplicates are more in A keep those in A, if they are more in B keep those in B. Just don't add both.
Richard MacCutchan 11-Dec-21 11:12am    
Start by sorting each list to make the comparisons easier. Then look for duplicates in the two lists. Once you find a duplicate vale then remove all of those values in the smaller subset from one list. In the example above you would remove the two number 2s, and the one 3, from list A. Once you have removed the duplicates the merged lists should provide a consistent result.

1 solution

Well it seems std::set_union does this. Nothing else is needed.
 
Share this answer
 
Comments
Shao Voon Wong 11-Dec-21 21:33pm    
The two vectors need to be sorted before calling std::set_union().

https://www.codeproject.com/Articles/1223131/STL-Set-Algorithm-Operators
Stefan_Lang 13-Dec-21 3:52am    
Very good article, must have missed that when it was published.
Shao Voon Wong 13-Dec-21 5:01am    
Thank you.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900