STL set_symmetric_difference usage

时间秒杀一切 提交于 2020-06-29 11:14:29

问题


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"


回答1:


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:

sort(A.begin(), A.end());
sort(B.begin(), B.end());
std::vector<int> c;
set_symmetric_difference(A.begin(), A.end(), 
                         B.begin(), B.end(), std::back_inserter(c));
return c;

This produces

21 43 76 78 87 98 123 234 312 342 645 654 756 876




回答2:


When I run your code, I get an exception from the vector iterator not be incrementable. I think the problem lies here:

vector c(A.size() < B.size() ? B.size() : A.size());

I changed it to:

vector c(A.size() + B.size());

and ran it with no exceptions. I also get the same numbers as what you wrote (the correct ones).



来源:https://stackoverflow.com/questions/11373583/stl-set-symmetric-difference-usage

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!