I was solving a programming problem, which wants to find the SYMMETRIC DIFFERENCE between two sets. I have solved it using STL’s set_symmetric_difference. I am given two vector<int>s, A and B:
A = {342,654,897,312,76,23,78}
B = {21,43,87,98,23,756,897,234,645,876,123}
Sould return (correct answer):
{ 21,43,76,78,87,98,123,234,312,342,645,654,756,876 }
But I get:
{ 21,43,76,78,87,98,123,234,312,342,645,65,756,876}
What is the problem ? Here is my code:
sort(A.begin(), A.end());
sort(B.begin(), B.end());
// allocate the smallest size of A,B as maximum size
vector<int> c(A.size() < B.size() ? B.size() : A.size());
vector<int>::iterator i;
i = set_symmetric_difference(A.begin(), A.end(), B.begin(), B.end(), c.begin());
return vector<int>(c.begin(), i);
NOTE:
I get correct answers for the rest of examples. This example only gives me this wrong answer.
I have tested it in Visual Studio, and got an error message: "Iterator not incrementable"
The problem is in the initialization of vector
c. The logic is slightly wrong in that the maximum size of the output range could be as large as the sum of the two input ranges. Since you don’t know the size a priori, you could be better off by starting with an empty output vector, and using push_back with an std::back_inserter instead:This produces