How to use std::ranges::set_symmetric_difference over a non sorted range?

31 views Asked by At

I have two vectors a and b and I need to iterate over every element that is NOT in both of them. So I decided to use std::ranges::set_symmetric_difference. To my dismay, this requires the vectors to be sorted, which they are not.

How can I, without sorting the vectors, create a range that contains the symmetric difference of the two sets?

Example code:

std::vector<int> a = {5, 3, 4, 1, 2};
std::vector<int> b = {3, 4, 5, 6, 7};
std::vector<int> c;

std::ranges::set_symmetric_difference(a, b, std::back_inserter(c));
std::ranges::for_each(c, [](const int i)
{
   std::cout << i << std::endl; 
});

This works fine if I sort a, but in my case I cannot.

Restriction: I can easily just iterate over the larger once and use a if check to skip any that are in the smaller one using std::ranges::contains. I do not want to do that. I want to iterate over one container or view or range that I can iterate over every element of without worry of running into one of the duplicated elements.

Bonus points if I do not need a vector c.

0

There are 0 answers