vector difference non-unique

Good day,

My problem is as follows:
1
2
v1 = 3 3 4 5 10 11 12 16 18 18 
v2 = 3 4 5 6 7 8 9 


I want the (set) difference of these two vectors (meaning; what is in v1, and not in v2) but keeping a count on the non-filtered out differences.

expected: v3 = 10 11 12 16 18 18

As can be seen, when a double element (such as '3') of v1 IS in v2, it acts if it were 'unique' rows, but when a double element (such as '18' IS NOT in v2 it copies both values to v3.

Some things I could use perhaps:
v1.erase(std::unique(v1.begin(), v1.end()), v1.end()); //Removes doubles

1
2
std::vector<int> result;
std::set_difference(v1.begin(), v1.end(), v2.begin(), v2.end(), std::inserter(result, result.end()));


Surely this is possible without going through many loops etc? Any help is appreciated.
Last edited on

The two vectors are sorted from low to high; if you can rely on this, or do it yourself each time with a sort, your algorithm needs just one pass through each vector.

Look at current value of v1. (i.e. first value, when we begin)
Look at current value of v2.
if v1 is greater than v2, move along one in v2 and start again
if v1 is same as v2, move v1 along one and start again
if v1 is less than v2, you've found a unique v1. Copy it to v3 and move along one in v1

Each time you move v2 along one, if you've come to the end of v2, copy all remaining of v1 to v3.
Each time you move v1 along one, if you've come to the end of v1, finish.

Last edited on
Topic archived. No new replies allowed.